home *** CD-ROM | disk | FTP | other *** search
/ PC Open 107 / PC Open 107 CD 1.bin / CD1 / INTERNET / EMAIL / pop file / setup.exe / $_1_ / DBI.pm < prev    next >
Encoding:
Perl POD Document  |  2003-12-01  |  232.6 KB  |  6,270 lines

  1. # $Id: DBI.pm,v 11.40 2003/11/27 23:29:06 timbo Exp $
  2. # vim: ts=8:sw=4
  3. #
  4. # Copyright (c) 1994-2003  Tim Bunce  Ireland
  5. #
  6. # See COPYRIGHT section in pod text below for usage and distribution rights.
  7. #
  8.  
  9. require 5.006_00;
  10.  
  11. BEGIN {
  12. $DBI::VERSION = "1.39"; # ==> ALSO update the version in the pod text below!
  13. }
  14.  
  15. =head1 NAME
  16.  
  17. DBI - Database independent interface for Perl
  18.  
  19. =head1 SYNOPSIS
  20.  
  21.   use DBI;
  22.  
  23.   @driver_names = DBI->available_drivers;
  24.   @data_sources = DBI->data_sources($driver_name, \%attr);
  25.  
  26.   $dbh = DBI->connect($data_source, $username, $auth, \%attr);
  27.  
  28.   $rv  = $dbh->do($statement);
  29.   $rv  = $dbh->do($statement, \%attr);
  30.   $rv  = $dbh->do($statement, \%attr, @bind_values);
  31.  
  32.   $ary_ref  = $dbh->selectall_arrayref($statement);
  33.   $hash_ref = $dbh->selectall_hashref($statement, $key_field);
  34.  
  35.   $ary_ref = $dbh->selectcol_arrayref($statement);
  36.   $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
  37.  
  38.   @row_ary  = $dbh->selectrow_array($statement);
  39.   $ary_ref  = $dbh->selectrow_arrayref($statement);
  40.   $hash_ref = $dbh->selectrow_hashref($statement);
  41.  
  42.   $sth = $dbh->prepare($statement);
  43.   $sth = $dbh->prepare_cached($statement);
  44.  
  45.   $rc = $sth->bind_param($p_num, $bind_value);
  46.   $rc = $sth->bind_param($p_num, $bind_value, $bind_type);
  47.   $rc = $sth->bind_param($p_num, $bind_value, \%attr);
  48.  
  49.   $rv = $sth->execute;
  50.   $rv = $sth->execute(@bind_values);
  51.  
  52.   $rc = $sth->bind_param_array($p_num, $bind_values, \%attr);
  53.   $rv = $sth->execute_array(\%attr);
  54.   $rv = $sth->execute_array(\%attr, @bind_values);
  55.  
  56.   $rc = $sth->bind_col($col_num, \$col_variable);
  57.   $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
  58.  
  59.   @row_ary  = $sth->fetchrow_array;
  60.   $ary_ref  = $sth->fetchrow_arrayref;
  61.   $hash_ref = $sth->fetchrow_hashref;
  62.  
  63.   $ary_ref  = $sth->fetchall_arrayref;
  64.   $ary_ref  = $sth->fetchall_arrayref( $slice, $max_rows );
  65.  
  66.   $hash_ref = $sth->fetchall_hashref( $key_field );
  67.  
  68.   $rv  = $sth->rows;
  69.  
  70.   $rc  = $dbh->begin_work;
  71.   $rc  = $dbh->commit;
  72.   $rc  = $dbh->rollback;
  73.  
  74.   $quoted_string = $dbh->quote($string);
  75.  
  76.   $rc  = $h->err;
  77.   $str = $h->errstr;
  78.   $rv  = $h->state;
  79.  
  80.   $rc  = $dbh->disconnect;
  81.  
  82. I<The synopsis above only lists the major methods and parameters.>
  83.  
  84.  
  85. =head2 GETTING HELP
  86.  
  87. If you have questions about DBI, you can get help from
  88. the I<dbi-users@perl.org> mailing list.
  89. You can get help on subscribing and using the list by emailing
  90. I<dbi-users-help@perl.org>.
  91.  
  92. (To help you make the best use of the dbi-users mailing list,
  93. and any other lists or forums you may use, I I<strongly>
  94. recommend that you read "How To Ask Questions The Smart Way"
  95. by Eric Raymond: L<http://www.catb.org/~esr/faqs/smart-questions.html>.)
  96.  
  97. The DBI home page at L<http://dbi.perl.org/> is always worth a visit
  98. and includes an FAQ and links to other resources.
  99.  
  100. Before asking any questions, reread this document, consult the
  101. archives and read the DBI FAQ. The archives are listed
  102. at the end of this document and on the DBI home page.
  103. An FAQ is installed as a L<DBI::FAQ> module so
  104. you can read it by executing C<perldoc DBI::FAQ>.
  105. However the DBI::FAQ module is currently (2003) outdated relative
  106. to the online FAQ on the DBI home page.
  107.  
  108. This document often uses terms like I<references>, I<objects>,
  109. I<methods>.  If you're not familar with those terms then it would
  110. be a good idea to read at least the following perl manuals first:
  111. L<perlreftut>, L<perldsc>, L<perllol>, and L<perlboot>.
  112.  
  113. Please note that Tim Bunce does not maintain the mailing lists or the
  114. web page (generous volunteers do that).  So please don't send mail
  115. directly to him; he just doesn't have the time to answer questions
  116. personally. The I<dbi-users> mailing list has lots of experienced
  117. people who should be able to help you if you need it. If you do email
  118. Tim he's very likely to just forward it to the mailing list.
  119.  
  120. =head2 NOTES
  121.  
  122. This is the DBI specification that corresponds to the DBI version 1.39
  123. (C<$Date: 2003/11/27 23:29:06 $>).
  124.  
  125. The DBI is evolving at a steady pace, so it's good to check that
  126. you have the latest copy.
  127.  
  128. The significant user-visible changes in each release are documented
  129. in the L<DBI::Changes> module so you can read them by executing
  130. C<perldoc DBI::Changes>.
  131.  
  132. Some DBI changes require changes in the drivers, but the drivers
  133. can take some time to catch up. Newer versions of the DBI have
  134. added features that may not yet be supported by the drivers you
  135. use.  Talk to the authors of your drivers if you need a new feature
  136. that's not yet supported.
  137.  
  138. Features added after DBI 1.21 (February 2002) are marked in the
  139. text with the version number of the DBI release they first appeared in.
  140.  
  141. Extensions to the DBI API often use the C<DBIx::*> namespace.
  142. See L</Naming Conventions and Name Space>. DBI extension modules
  143. can be found at L<"http://search.cpan.org/search?mode=module&query=DBIx%3A%3A">.
  144. And all modules related to the DBI can be found at
  145. L<"http://search.cpan.org/search?query=DBI&mode=all">.
  146.  
  147. =cut
  148.  
  149. # The POD text continues at the end of the file.
  150.  
  151.  
  152. package DBI;
  153.  
  154. my $Revision = substr(q$Revision: 11.40 $, 10);
  155.  
  156. use Carp();
  157. use DynaLoader ();
  158. use Exporter ();
  159.  
  160. BEGIN {
  161. @ISA = qw(Exporter DynaLoader);
  162.  
  163. # Make some utility functions available if asked for
  164. @EXPORT    = ();            # we export nothing by default
  165. @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags:
  166. %EXPORT_TAGS = (
  167.    sql_types => [ qw(
  168.     SQL_GUID
  169.     SQL_WLONGVARCHAR
  170.     SQL_WVARCHAR
  171.     SQL_WCHAR
  172.     SQL_BIT
  173.     SQL_TINYINT
  174.     SQL_LONGVARBINARY
  175.     SQL_VARBINARY
  176.     SQL_BINARY
  177.     SQL_LONGVARCHAR
  178.     SQL_UNKNOWN_TYPE
  179.     SQL_ALL_TYPES
  180.     SQL_CHAR
  181.     SQL_NUMERIC
  182.     SQL_DECIMAL
  183.     SQL_INTEGER
  184.     SQL_SMALLINT
  185.     SQL_FLOAT
  186.     SQL_REAL
  187.     SQL_DOUBLE
  188.     SQL_DATETIME
  189.     SQL_DATE
  190.     SQL_INTERVAL
  191.     SQL_TIME
  192.     SQL_TIMESTAMP
  193.     SQL_VARCHAR
  194.     SQL_BOOLEAN
  195.     SQL_UDT
  196.     SQL_UDT_LOCATOR
  197.     SQL_ROW
  198.     SQL_REF
  199.     SQL_BLOB
  200.     SQL_BLOB_LOCATOR
  201.     SQL_CLOB
  202.     SQL_CLOB_LOCATOR
  203.     SQL_ARRAY
  204.     SQL_ARRAY_LOCATOR
  205.     SQL_MULTISET
  206.     SQL_MULTISET_LOCATOR
  207.     SQL_TYPE_DATE
  208.     SQL_TYPE_TIME
  209.     SQL_TYPE_TIMESTAMP
  210.     SQL_TYPE_TIME_WITH_TIMEZONE
  211.     SQL_TYPE_TIMESTAMP_WITH_TIMEZONE
  212.     SQL_INTERVAL_YEAR
  213.     SQL_INTERVAL_MONTH
  214.     SQL_INTERVAL_DAY
  215.     SQL_INTERVAL_HOUR
  216.     SQL_INTERVAL_MINUTE
  217.     SQL_INTERVAL_SECOND
  218.     SQL_INTERVAL_YEAR_TO_MONTH
  219.     SQL_INTERVAL_DAY_TO_HOUR
  220.     SQL_INTERVAL_DAY_TO_MINUTE
  221.     SQL_INTERVAL_DAY_TO_SECOND
  222.     SQL_INTERVAL_HOUR_TO_MINUTE
  223.     SQL_INTERVAL_HOUR_TO_SECOND
  224.     SQL_INTERVAL_MINUTE_TO_SECOND
  225.    ) ],
  226.    utils     => [ qw(
  227.     neat neat_list dump_results looks_like_number
  228.    ) ],
  229.    profile   => [ qw(
  230.     dbi_profile dbi_profile_merge dbi_time
  231.    ) ], # notionally "in" DBI::Profile and normally imported from there
  232. );
  233.  
  234. $DBI::dbi_debug = $ENV{DBI_TRACE} || $ENV{PERL_DBI_DEBUG} || 0;
  235. $DBI::neat_maxlen = 400;
  236.  
  237. # If you get an error here like "Can't find loadable object ..."
  238. # then you haven't installed the DBI correctly. Read the README
  239. # then install it again.
  240. if ( $ENV{DBI_PUREPERL} ) {
  241.     eval { bootstrap DBI } if       $ENV{DBI_PUREPERL} == 1;
  242.     require DBI::PurePerl  if $@ or $ENV{DBI_PUREPERL} >= 2;
  243.     $DBI::PurePerl ||= 0; # just to silence "only used once" warnings
  244. }
  245. else {
  246.     bootstrap DBI;
  247. }
  248.  
  249. $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ];
  250.  
  251. Exporter::export_ok_tags(keys %EXPORT_TAGS);
  252.  
  253. }
  254.  
  255. *trace_msg = \&DBD::_::common::trace_msg;
  256. *set_err   = \&DBD::_::common::set_err;
  257.  
  258. use strict;
  259.  
  260. $DBI::connect_via = "connect";
  261.  
  262. # check if user wants a persistent database connection ( Apache + mod_perl )
  263. if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
  264.     $DBI::connect_via = "Apache::DBI::connect";
  265.     DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n");
  266. }
  267.  
  268.  
  269. if ($DBI::dbi_debug) {
  270.     @DBI::dbi_debug = ($DBI::dbi_debug);
  271.  
  272.     if ($DBI::dbi_debug !~ m/^\d$/) {
  273.     # dbi_debug is a file name to write trace log to.
  274.     # Default level is 2 but if file starts with "digits=" then the
  275.     # digits (and equals) are stripped off and used as the level
  276.     unshift @DBI::dbi_debug, 2;
  277.     @DBI::dbi_debug = ($1,$2) if $DBI::dbi_debug =~ m/^(\d+)=(.*)/;
  278.     $DBI::dbi_debug = $DBI::dbi_debug[0];
  279.     }
  280.     DBI->trace(@DBI::dbi_debug);
  281. }
  282.  
  283. %DBI::installed_drh = ();  # maps driver names to installed driver handles
  284.  
  285.  
  286. # Setup special DBI dynamic variables. See DBI::var::FETCH for details.
  287. # These are dynamically associated with the last handle used.
  288. tie $DBI::err,    'DBI::var', '*err';    # special case: referenced via IHA list
  289. tie $DBI::state,  'DBI::var', '"state';  # special case: referenced via IHA list
  290. tie $DBI::lasth,  'DBI::var', '!lasth';  # special case: return boolean
  291. tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg
  292. tie $DBI::rows,   'DBI::var', '&rows';   # call &rows   in last used pkg
  293. sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
  294. sub DBI::var::STORE    { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") }
  295.  
  296. {   # used to catch DBI->{Attrib} mistake
  297.     sub DBI::DBI_tie::TIEHASH { bless {} }
  298.     sub DBI::DBI_tie::STORE   { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");}
  299.     *DBI::DBI_tie::FETCH = \&DBI::DBI_tie::STORE;
  300. }
  301. tie %DBI::DBI => 'DBI::DBI_tie';
  302.  
  303. # --- Driver Specific Prefix Registry ---
  304.  
  305. my $dbd_prefix_registry = {
  306.   ad_      => { class => 'DBD::AnyData',    },
  307.   ado_     => { class => 'DBD::ADO',        },
  308.   best_    => { class => 'DBD::BestWins',    },
  309.   csv_     => { class => 'DBD::CSV',        },
  310.   db2_     => { class => 'DBD::DB2',        },
  311.   dbi_     => { class => 'DBI',            },
  312.   df_      => { class => 'DBD::DF',        },
  313.   f_       => { class => 'DBD::File',        },
  314.   file_    => { class => 'DBD::TextFile',    },
  315.   ib_      => { class => 'DBD::InterBase',    },
  316.   ing_     => { class => 'DBD::Ingres',        },
  317.   ix_      => { class => 'DBD::Informix',    },
  318.   msql_    => { class => 'DBD::mSQL',        },
  319.   mysql_   => { class => 'DBD::mysql',        },
  320.   odbc_    => { class => 'DBD::ODBC',        },
  321.   ora_     => { class => 'DBD::Oracle',        },
  322.   pg_      => { class => 'DBD::Pg',        },
  323.   proxy_   => { class => 'DBD::Proxy',        },
  324.   rdb_     => { class => 'DBD::RDB',        },
  325.   sapdb_   => { class => 'DBD::SAP_DB',        },
  326.   solid_   => { class => 'DBD::Solid',        },
  327.   sql_     => { class => 'SQL::Statement',    },
  328.   syb_     => { class => 'DBD::Sybase',        },
  329.   sponge_  => { class => 'DBD::Sponge',        },
  330.   tdat_    => { class => 'DBD::Teradata',    },
  331.   tmpl_    => { class => 'DBD::Template',    },
  332.   tmplss_  => { class => 'DBD::TemplateSS',    },
  333.   tuber_   => { class => 'DBD::Tuber',        },
  334.   uni_     => { class => 'DBD::Unify',        },
  335.   xbase_   => { class => 'DBD::XBase',        },
  336.   xl_      => { class => 'DBD::Excel',        },
  337. };
  338.  
  339. sub dump_dbd_registry {
  340.     require Data::Dumper;
  341.     print Data::Dumper::Dump($dbd_prefix_registry);
  342. }
  343.  
  344. # --- Dynamically create the DBI Standard Interface
  345.  
  346. my $keeperr = { O=>0x0004 };
  347.  
  348. my @TieHash_IF = (    # Generic Tied Hash Interface
  349.     'STORE'   => { O=>0x0418 | 0x4 },
  350.     'FETCH'   => { O=>0x0404 },
  351.     'FIRSTKEY'=> $keeperr,
  352.     'NEXTKEY' => $keeperr,
  353.     'EXISTS'  => $keeperr,
  354.     'CLEAR'   => $keeperr,
  355.     'DESTROY' => $keeperr,
  356. );
  357. my @Common_IF = (    # Interface functions common to all DBI classes
  358.     func    =>    {                O=>0x0006    },
  359.     'trace' =>    { U =>[1,3,'[$trace_level, [$filename]]'],    O=>0x0004 },
  360.     trace_msg =>    { U =>[2,3,'$message_text [, $min_level ]' ],    O=>0x0004, T=>8 },
  361.     debug   =>    { U =>[1,2,'[$debug_level]'],    O=>0x0004 }, # old name for trace
  362.     dump_handle  =>    { U =>[1,3,'[$message [, $level]]'],    O=>0x0004 },
  363.     private_data =>    { U =>[1,1],            O=>0x0004 },
  364.     err     =>    $keeperr,
  365.     errstr  =>    $keeperr,
  366.     state   =>    { U =>[1,1],    O=>0x0004 },
  367.     set_err =>    {        O=>0x0010 },
  368.     _not_impl =>    undef,
  369.     can    =>    { O=>0x0100 }, # special case, see dispatch
  370. );
  371.  
  372. %DBI::DBI_methods = ( # Define the DBI interface methods per class:
  373.  
  374.     dr => {        # Database Driver Interface
  375.     @Common_IF,
  376.     @TieHash_IF,
  377.     'connect'  =>    { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 },
  378.     'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 },
  379.     'disconnect_all'=>{ U =>[1,1], O=>0x0800 },
  380.     data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800 },
  381.     default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] },
  382.     },
  383.     db => {        # Database Session Class Interface
  384.     @Common_IF,
  385.     @TieHash_IF,
  386.     data_sources    => { U =>[1,2,'[\%attr]' ], O=>0x0200 },
  387.     take_imp_data    => { U =>[1,1], },
  388.     clone       => { U =>[1,1,''] },
  389.     connected       => { O=>0x0100 },
  390.     begin_work       => { U =>[1,2,'[ \%attr ]'], O=>0x0400 },
  391.     commit         => { U =>[1,1], O=>0x0480|0x0800 },
  392.     rollback       => { U =>[1,1], O=>0x0480|0x0800 },
  393.     'do'           => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x0200 },
  394.     last_insert_id    => { U =>[3,4,'$table_name, $field_name [, \%attr ]'], O=>0x0100 },
  395.     preparse        => {  }, # XXX
  396.     prepare        => { U =>[2,3,'$statement [, \%attr]'], O=>0x0200 },
  397.     prepare_cached    => { U =>[2,4,'$statement [, \%attr [, $allow_active ] ]'] },
  398.     selectrow_array    => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
  399.     selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
  400.     selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
  401.     selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
  402.     selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'] },
  403.     selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
  404.     ping           => { U =>[1,1], O=>0x0404 },
  405.     disconnect     => { U =>[1,1], O=>0x0400|0x0800 },
  406.     quote          => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430 },
  407.     quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ],    O=>0x0430 },
  408.     rows           => $keeperr,
  409.  
  410.     tables          => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x0200 },
  411.     table_info      => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ],    O=>0x0200|0x0800 },
  412.     column_info     => { U =>[1,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x0200|0x0800 },
  413.     primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ],    O=>0x0200|0x0800 },
  414.     primary_key     => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ],    O=>0x0200 },
  415.     foreign_key_info=> { U =>[1,7,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table' ], O=>0x0200|0x0800 },
  416.     type_info_all    => { U =>[1,1], O=>0x0200|0x0800 },
  417.     type_info    => { U =>[1,2,'$data_type'], O=>0x0200 },
  418.     get_info    => { U =>[2,2,'$info_type'], O=>0x0200|0x0800 },
  419.     },
  420.     st => {        # Statement Class Interface
  421.     @Common_IF,
  422.     @TieHash_IF,
  423.     bind_col    => { U =>[3,4,'$column, \\$var [, \%attr]'] },
  424.     bind_columns    => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] },
  425.     bind_param    => { U =>[3,4,'$parameter, $var [, \%attr]'] },
  426.     bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] },
  427.     execute        => { U =>[1,0,'[@args]'], O=>0x40 },
  428.  
  429.     bind_param_array  => { U =>[3,4,'$parameter, $var [, \%attr]'] },
  430.     bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] },
  431.     execute_array     => { U =>[2,0,'\\%attribs [, @args]'] },
  432.     execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'] },
  433.  
  434.     fetch          => undef, # alias for fetchrow_arrayref
  435.     fetchrow_arrayref => undef,
  436.     fetchrow_hashref  => undef,
  437.     fetchrow_array    => undef,
  438.     fetchrow         => undef, # old alias for fetchrow_array
  439.  
  440.     fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] },
  441.     fetchall_hashref  => { U =>[2,2,'$key_field'] },
  442.  
  443.     blob_read  =>    { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] },
  444.     blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] },
  445.     dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] },
  446.     more_results => { U =>[1,1] },
  447.     finish     =>     { U =>[1,1] },
  448.     cancel     =>     { U =>[1,1], O=>0x0800 },
  449.     rows       =>    $keeperr,
  450.  
  451.     _get_fbav    => undef,
  452.     _set_fbav    => { T=>6 },
  453.     },
  454. );
  455.  
  456. my($class, $method);
  457. foreach $class (keys %DBI::DBI_methods){
  458.     my %pkgif = %{ $DBI::DBI_methods{$class} };
  459.     foreach $method (keys %pkgif){
  460.     DBI->_install_method("DBI::${class}::$method", 'DBI.pm',
  461.             $pkgif{$method});
  462.     }
  463. }
  464.  
  465.  
  466. # End of init code
  467.  
  468.  
  469. END {
  470.     return unless defined &DBI::trace_msg; # return unless bootstrap'd ok
  471.     local ($!,$?);
  472.     DBI->trace_msg("    -- DBI::END\n", 2);
  473.     # Let drivers know why we are calling disconnect_all:
  474.     $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1;    # avoid typo warning
  475.     DBI->disconnect_all() if %DBI::installed_drh;
  476. }
  477.  
  478.  
  479. sub CLONE {
  480.     my $olddbis = $DBI::_dbistate;
  481.     _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure
  482.     %DBI::installed_drh = ();    # clear loaded drivers so they have a chance to reinitialize
  483.     DBI->trace_msg(sprintf "CLONE DBI for new thread %s\n",
  484.     $DBI::PurePerl ? "" : sprintf("(dbis %x -> %x)",$olddbis, $DBI::_dbistate));
  485. }
  486.     
  487.  
  488. # --- The DBI->connect Front Door methods
  489.  
  490. sub connect_cached {
  491.     # XXX we expect Apache::DBI users to still call connect()
  492.     my ($class, $dsn, $user, $pass, $attr) = @_;
  493.     ($attr ||= {})->{dbi_connect_method} = 'connect_cached';
  494.     return $class->connect($dsn, $user, $pass, $attr);
  495. }
  496.  
  497. sub connect {
  498.     my $class = shift;
  499.     my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_;
  500.     my $driver;
  501.  
  502.     if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style
  503.     Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions");
  504.         ($old_driver, $attr) = ($attr, $old_driver);
  505.     }
  506.  
  507.     my $connect_meth = $attr->{dbi_connect_method};
  508.     $connect_meth ||= $DBI::connect_via;    # fallback to default
  509.  
  510.     $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver;
  511.  
  512.     if ($DBI::dbi_debug) {
  513.     local $^W = 0;
  514.     pop @_ if $connect_meth ne 'connect';
  515.     my @args = @_; $args[2] = '****'; # hide password
  516.     DBI->trace_msg("    -> $class->$connect_meth(".join(", ",@args).")\n");
  517.     }
  518.     Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])')
  519.     if (ref $old_driver or ($attr and not ref $attr) or ref $pass);
  520.  
  521.     # extract dbi:driver prefix from $dsn into $1
  522.     $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i
  523.             or '' =~ /()/; # ensure $1 etc are empty if match fails
  524.     my $driver_attrib_spec = $2 || '';
  525.  
  526.     # Set $driver. Old style driver, if specified, overrides new dsn style.
  527.     $driver = $old_driver || $1 || $ENV{DBI_DRIVER}
  528.     or Carp::croak("Can't connect(@_), no database driver specified "
  529.         ."and DBI_DSN env var not set");
  530.  
  531.     if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') {
  532.     my $proxy = 'Proxy';
  533.     if ($ENV{DBI_AUTOPROXY} =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) {
  534.         $proxy = $1;
  535.         my $attr_spec = $2 || '';
  536.         $driver_attrib_spec = ($driver_attrib_spec) ? "$driver_attrib_spec,$attr_spec" : $attr_spec;
  537.     }
  538.     $dsn = "$ENV{DBI_AUTOPROXY};dsn=dbi:$driver:$dsn";
  539.     $driver = $proxy;
  540.     DBI->trace_msg("       DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n");
  541.     }
  542.  
  543.     my %attributes;    # take a copy we can delete from
  544.     if ($old_driver) {
  545.     %attributes = %$attr if $attr;
  546.     }
  547.     else {        # new-style connect so new default semantics
  548.     %attributes = (
  549.         PrintError => 1,
  550.         AutoCommit => 1,
  551.         ref $attr           ? %$attr : (),
  552.         # attributes in DSN take precedence over \%attr connect parameter
  553.         $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (),
  554.     );
  555.     }
  556.     $attr = \%attributes; # now set $attr to refer to our local copy
  557.  
  558.     my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver)
  559.     or die "panic: $class->install_driver($driver) failed";
  560.  
  561.     # attributes in DSN take precedence over \%attr connect parameter
  562.     $user =        $attr->{Username} if defined $attr->{Username};
  563.     $pass = delete $attr->{Password} if defined $attr->{Password};
  564.  
  565.     ($user, $pass) = $drh->default_user($user, $pass, $attr)
  566.     if !(defined $user && defined $pass);
  567.  
  568.     $attr->{Username} = $user;    # store username as attribute
  569.  
  570.     my $connect_closure = sub {
  571.     my ($old_dbh, $override_attr) = @_;
  572.  
  573.     my $attr = {
  574.         # copy so we can edit them each time we're called
  575.         %attributes,
  576.         # merge in modified attr in %$old_dbh, this should also copy in
  577.         # the dbi_connect_closure attribute so we can reconnect again.
  578.         %{ $override_attr || {} },
  579.     };
  580.     #warn "connect_closure: ".Data::Dumper::Dumper([\%attributes, $override_attr]);
  581.  
  582.     my $dbh;
  583.     unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) {
  584.         $user = '' if !defined $user;
  585.         $dsn = '' if !defined $dsn;
  586.         my $errstr = $drh->errstr;
  587.         $errstr = '(no error string)' if !defined $errstr;
  588.         my $msg = "$class connect('$dsn','$user',...) failed: $errstr";
  589.         DBI->trace_msg("       $msg\n");
  590.         unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) {
  591.         Carp::croak($msg) if $attr->{RaiseError};
  592.         Carp::carp ($msg) if $attr->{PrintError};
  593.         }
  594.         $! = 0; # for the daft people who do DBI->connect(...) || die "$!";
  595.         return $dbh; # normally undef, but HandleError could change it
  596.     }
  597.  
  598.     # handle basic RootClass subclassing:
  599.     my $rebless_class = $attr->{RootClass} || ($class ne 'DBI' ? $class : '');
  600.     if ($rebless_class) {
  601.         no strict 'refs';
  602.         if ($attr->{RootClass}) {    # explicit attribute (rather than static call)
  603.         delete $attr->{RootClass};
  604.         DBI::_load_class($rebless_class, 0);
  605.         }
  606.         unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) {
  607.         Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored");
  608.         $rebless_class = undef;
  609.         $class = 'DBI';
  610.         }
  611.         else {
  612.         $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db
  613.         DBI::_set_isa([$rebless_class], 'DBI');     # sets up both '::db' and '::st'
  614.         DBI::_rebless($dbh, $rebless_class);        # appends '::db'
  615.         }
  616.     }
  617.  
  618.     if (%$attr) {
  619.  
  620.         DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, delete $attr->{DbTypeSubclass}, $attr)
  621.         if $attr->{DbTypeSubclass};
  622.  
  623.         my $a;
  624.         foreach $a (qw(RaiseError PrintError AutoCommit)) { # do these first
  625.         next unless  exists $attr->{$a};
  626.         $dbh->{$a} = delete $attr->{$a};
  627.         }
  628.         foreach $a (keys %$attr) {
  629.         $dbh->{$a} = $attr->{$a};
  630.         }
  631.     }
  632.  
  633.     # if we've been subclassed then let the subclass know that we're connected
  634.     $dbh->connected($dsn, $user, $pass, $attr) if ref $dbh ne 'DBI::db';
  635.  
  636.     DBI->trace_msg("    <- connect= $dbh\n") if $DBI::dbi_debug;
  637.  
  638.     return $dbh;
  639.     };
  640.  
  641.     my $dbh = &$connect_closure(undef, undef);
  642.  
  643.     $dbh->{dbi_connect_closure} = $connect_closure if $dbh;
  644.  
  645.     return $dbh;
  646. }
  647.  
  648.  
  649. sub disconnect_all {
  650.     keys %DBI::installed_drh; # reset iterator
  651.     while ( my ($name, $drh) = each %DBI::installed_drh ) {
  652.     $drh->disconnect_all() if ref $drh;
  653.     }
  654. }
  655.  
  656.  
  657. sub disconnect {        # a regular beginners bug
  658.     Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)");
  659. }
  660.  
  661.  
  662. sub install_driver {        # croaks on failure
  663.     my $class = shift;
  664.     my($driver, $attr) = @_;
  665.     my $drh;
  666.  
  667.     $driver ||= $ENV{DBI_DRIVER} || '';
  668.  
  669.     # allow driver to be specified as a 'dbi:driver:' string
  670.     $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
  671.  
  672.     Carp::croak("usage: $class->install_driver(\$driver [, \%attr])")
  673.         unless ($driver and @_<=3);
  674.  
  675.     # already installed
  676.     return $drh if $drh = $DBI::installed_drh{$driver};
  677.  
  678.     $class->trace_msg("    -> $class->install_driver($driver"
  679.             .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n")
  680.     if $DBI::dbi_debug;
  681.  
  682.     # --- load the code
  683.     my $driver_class = "DBD::$driver";
  684.     eval qq{package            # hide from PAUSE
  685.         DBI::_firesafe;        # just in case
  686.         require $driver_class;    # load the driver
  687.     };
  688.     if ($@) {
  689.     my $err = $@;
  690.     my $advice = "";
  691.     if ($err =~ /Can't find loadable object/) {
  692.         $advice = "Perhaps DBD::$driver was statically linked into a new perl binary."
  693.          ."\nIn which case you need to use that new perl binary."
  694.          ."\nOr perhaps only the .pm file was installed but not the shared object file."
  695.     }
  696.     elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) {
  697.         my @drv = $class->available_drivers(1);
  698.         $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n"
  699.              ."or perhaps the capitalisation of '$driver' isn't right.\n"
  700.              ."Available drivers: ".join(", ", @drv).".";
  701.     }
  702.     elsif ($err =~ /Can't load .*? for module DBD::/) {
  703.         $advice = "Perhaps a required shared library or dll isn't installed where expected";
  704.     }
  705.     elsif ($err =~ /Can't locate .*? in \@INC/) {
  706.         $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed";
  707.     }
  708.     Carp::croak("install_driver($driver) failed: $err$advice\n");
  709.     }
  710.     if ($DBI::dbi_debug) {
  711.     no strict 'refs';
  712.     (my $driver_file = $driver_class) =~ s/::/\//g;
  713.     my $dbd_ver = ${"$driver_class\::VERSION"} || "undef";
  714.     $class->trace_msg("       install_driver: $driver_class version $dbd_ver"
  715.         ." loaded from $INC{qq($driver_file.pm)}\n");
  716.     }
  717.  
  718.     # --- do some behind-the-scenes checks and setups on the driver
  719.     $class->setup_driver($driver_class);
  720.  
  721.     # --- run the driver function
  722.     $drh = eval { $driver_class->driver($attr || {}) };
  723.     unless ($drh && ref $drh && !$@) {
  724.     my $advice = "";
  725.     # catch people on case in-sensitive systems using the wrong case
  726.     $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right."
  727.         if $@ =~ /locate object method/;
  728.     Carp::croak("$driver_class initialisation failed: $@$advice");
  729.     }
  730.  
  731.     $DBI::installed_drh{$driver} = $drh;
  732.     $class->trace_msg("    <- install_driver= $drh\n") if $DBI::dbi_debug;
  733.     $drh;
  734. }
  735.  
  736. *driver = \&install_driver;    # currently an alias, may change
  737.  
  738.  
  739. sub setup_driver {
  740.     my ($class, $driver_class) = @_;
  741.     my $type;
  742.     foreach $type (qw(dr db st)){
  743.     my $class = $driver_class."::$type";
  744.     no strict 'refs';
  745.     push @{"${class}::ISA"},     "DBD::_::$type"
  746.         unless UNIVERSAL::isa($class, "DBD::_::$type");
  747.     my $mem_class = "DBD::_mem::$type";
  748.     push @{"${class}_mem::ISA"}, $mem_class
  749.         unless UNIVERSAL::isa("${class}_mem", $mem_class)
  750.         or $DBI::PurePerl;
  751.     }
  752. }
  753.  
  754.  
  755. sub _rebless {
  756.     my $dbh = shift;
  757.     my ($outer, $inner) = DBI::_handles($dbh);
  758.     my $class = shift(@_).'::db';
  759.     bless $inner => $class;
  760.     bless $outer => $class; # outer last for return
  761. }
  762.  
  763.  
  764. sub _set_isa {
  765.     my ($classes, $topclass) = @_;
  766.     my $trace = DBI->trace_msg("       _set_isa([@$classes])\n");
  767.     foreach my $suffix ('::db','::st') {
  768.     my $previous = $topclass || 'DBI'; # trees are rooted here
  769.     foreach my $class (@$classes) {
  770.         my $base_class = $previous.$suffix;
  771.         my $sub_class  = $class.$suffix;
  772.         my $sub_class_isa  = "${sub_class}::ISA";
  773.         no strict 'refs';
  774.         if (@$sub_class_isa) {
  775.         DBI->trace_msg("       $sub_class_isa skipped (already set to @$sub_class_isa)\n")
  776.             if $trace;
  777.         }
  778.         else {
  779.         @$sub_class_isa = ($base_class) unless @$sub_class_isa;
  780.         DBI->trace_msg("       $sub_class_isa = $base_class\n")
  781.             if $trace;
  782.         }
  783.         $previous = $class;
  784.     }
  785.     }
  786. }
  787.  
  788.  
  789. sub _rebless_dbtype_subclass {
  790.     my ($dbh, $rootclass, $DbTypeSubclass, $attr) = @_;
  791.     # determine the db type names for class hierarchy
  792.     my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass, $attr);
  793.     # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc)
  794.     $_ = $rootclass.'::'.$_ foreach (@hierarchy);
  795.     # load the modules from the 'top down'
  796.     DBI::_load_class($_, 1) foreach (reverse @hierarchy);
  797.     # setup class hierarchy if needed, does both '::db' and '::st'
  798.     DBI::_set_isa(\@hierarchy, $rootclass);
  799.     # finally bless the handle into the subclass
  800.     DBI::_rebless($dbh, $hierarchy[0]);
  801. }
  802.  
  803.  
  804. sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC
  805.     my ($dbh, $DbTypeSubclass, $attr) = @_;
  806.  
  807.     if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') {
  808.     # treat $DbTypeSubclass as a comma separated list of names
  809.     my @dbtypes = split /\s*,\s*/, $DbTypeSubclass;
  810.     $dbh->trace_msg("    DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n");
  811.     return @dbtypes;
  812.     }
  813.  
  814.     # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future?
  815.  
  816.     my $driver = $dbh->{Driver}->{Name};
  817.     if ( $driver eq 'Proxy' ) {
  818.         # XXX Looking into the internals of DBD::Proxy is questionable!
  819.         ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i
  820.         or die "Can't determine driver name from proxy";
  821.     }
  822.  
  823.     my @dbtypes = (ucfirst($driver));
  824.     if ($driver eq 'ODBC' || $driver eq 'ADO') {
  825.     # XXX will move these out and make extensible later:
  826.     my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar'
  827.     my %_dbtype_name_map = (
  828.          'Microsoft SQL Server'    => 'MSSQL',
  829.          'SQL Server'        => 'Sybase',
  830.          'Adaptive Server Anywhere'    => 'ASAny',
  831.          'ADABAS D'            => 'AdabasD',
  832.     );
  833.  
  834.         my $name;
  835.     $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME
  836.         if $driver eq 'ODBC';
  837.     $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value
  838.         if $driver eq 'ADO';
  839.     die "Can't determine driver name! ($DBI::errstr)\n"
  840.         unless $name;
  841.  
  842.     my $dbtype;
  843.         if ($_dbtype_name_map{$name}) {
  844.             $dbtype = $_dbtype_name_map{$name};
  845.         }
  846.     else {
  847.         if ($name =~ /($_dbtype_name_regexp)/) {
  848.         $dbtype = lc($1);
  849.         }
  850.         else { # generic mangling for other names:
  851.         $dbtype = lc($name);
  852.         }
  853.         $dbtype =~ s/\b(\w)/\U$1/g;
  854.         $dbtype =~ s/\W+/_/g;
  855.     }
  856.     # add ODBC 'behind' ADO
  857.     push    @dbtypes, 'ODBC' if $driver eq 'ADO';
  858.     # add discovered dbtype in front of ADO/ODBC
  859.     unshift @dbtypes, $dbtype;
  860.     }
  861.     @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes)
  862.     if (ref $DbTypeSubclass eq 'CODE');
  863.     $dbh->trace_msg("    DbTypeSubclass($DbTypeSubclass)=@dbtypes\n");
  864.     return @dbtypes;
  865. }
  866.  
  867. sub _load_class {
  868.     my ($load_class, $missing_ok) = @_;
  869.     #DBI->trace_msg("    _load_class($load_class, $missing_ok)\n");
  870.     no strict 'refs';
  871.     return 1 if @{"$load_class\::ISA"};    # already loaded/exists
  872.     (my $module = $load_class) =~ s!::!/!g;
  873.     #DBI->trace_msg("    _load_class require $module\n");
  874.     eval { require "$module.pm"; };
  875.     return 1 unless $@;
  876.     return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/;
  877.     die; # propagate $@;
  878. }
  879.  
  880.  
  881. sub init_rootclass {    # deprecated
  882.     return 1;
  883. }
  884.  
  885.  
  886. *internal = \&DBD::Switch::dr::driver;
  887.  
  888.  
  889. sub available_drivers {
  890.     my($quiet) = @_;
  891.     my(@drivers, $d, $f);
  892.     local(*DBI::DIR, $@);
  893.     my(%seen_dir, %seen_dbd);
  894.     my $haveFileSpec = eval { require File::Spec };
  895.     foreach $d (@INC){
  896.     chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
  897.     my $dbd_dir =
  898.         ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD");
  899.     next unless -d $dbd_dir;
  900.     next if $seen_dir{$d};
  901.     $seen_dir{$d} = 1;
  902.     # XXX we have a problem here with case insensitive file systems
  903.     # XXX since we can't tell what case must be used when loading.
  904.     opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n";
  905.     foreach $f (readdir(DBI::DIR)){
  906.         next unless $f =~ s/\.pm$//;
  907.         next if $f eq 'NullP';
  908.         if ($seen_dbd{$f}){
  909.         Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
  910.             unless $quiet;
  911.             } else {
  912.         push(@drivers, $f);
  913.         }
  914.         $seen_dbd{$f} = $d;
  915.     }
  916.     closedir(DBI::DIR);
  917.     }
  918.  
  919.     # "return sort @drivers" will not DWIM in scalar context.
  920.     return wantarray ? sort @drivers : @drivers;
  921. }
  922.  
  923. sub installed_versions {
  924.     my ($class, $quiet) = @_;
  925.     my %error;
  926.     my %version = ( DBI => $DBI::VERSION );
  927.     $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION
  928.     if $DBI::PurePerl;
  929.     for my $driver ($class->available_drivers($quiet)) {
  930.     next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC;
  931.     my $drh = eval {
  932.         local $SIG{__WARN__} = sub {};
  933.         $class->install_driver($driver);
  934.     };
  935.     ($error{"DBD::$driver"}=$@),next if $@;
  936.     no strict 'refs';
  937.     my $vers = ${"DBD::$driver" . '::VERSION'};
  938.     $version{"DBD::$driver"} = $vers || '?';
  939.     }
  940.     if (wantarray) {
  941.        return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version;
  942.     }
  943.     if (!defined wantarray) {    # void context
  944.     require Config;        # add more detail
  945.     $version{OS}   = "$^O\t($Config::Config{osvers})";
  946.     $version{Perl} = "$]\t($Config::Config{archname})";
  947.     $version{$_}   = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_})
  948.         for keys %error;
  949.     printf "  %-16s: %s\n",$_,$version{$_}
  950.         for reverse sort keys %version;
  951.     }
  952.     return \%version;
  953. }
  954.  
  955.  
  956. sub data_sources {
  957.     my ($class, $driver, @other) = @_;
  958.     my $drh = $class->install_driver($driver);
  959.     my @ds = $drh->data_sources(@other);
  960.     return @ds;
  961. }
  962.  
  963. sub neat_list {
  964.     my ($listref, $maxlen, $sep) = @_;
  965.     $maxlen = 0 unless defined $maxlen;    # 0 == use internal default
  966.     $sep = ", " unless defined $sep;
  967.     join($sep, map { neat($_,$maxlen) } @$listref);
  968. }
  969.  
  970.  
  971. sub dump_results {    # also aliased as a method in DBD::_::st
  972.     my ($sth, $maxlen, $lsep, $fsep, $fh) = @_;
  973.     return 0 unless $sth;
  974.     $maxlen ||= 35;
  975.     $lsep   ||= "\n";
  976.     $fh ||= \*STDOUT;
  977.     my $rows = 0;
  978.     my $ref;
  979.     while($ref = $sth->fetch) {
  980.     print $fh $lsep if $rows++ and $lsep;
  981.     my $str = neat_list($ref,$maxlen,$fsep);
  982.     print $fh $str;    # done on two lines to avoid 5.003 errors
  983.     }
  984.     print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
  985.     $rows;
  986. }
  987.  
  988.  
  989.  
  990. sub connect_test_perf {
  991.     my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
  992.     Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr;
  993.     # these are non standard attributes just for this special method
  994.     my $loops ||= $attr->{dbi_loops} || 5;
  995.     my $par   ||= $attr->{dbi_par}   || 1;    # parallelism
  996.     my $verb  ||= $attr->{dbi_verb}  || 1;
  997.     print "$dsn: testing $loops sets of $par connections:\n";
  998.     require Benchmark;
  999.     require "FileHandle.pm";    # don't let toke.c create empty FileHandle package
  1000.     $| = 1;
  1001.     my $t0 = new Benchmark;        # not currently used
  1002.     my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n");
  1003.     my $t1 = new Benchmark;
  1004.     my $loop;
  1005.     for $loop (1..$loops) {
  1006.     my @cons;
  1007.     print "Connecting... " if $verb;
  1008.     for (1..$par) {
  1009.         print "$_ ";
  1010.         push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
  1011.             or Carp::croak("Can't connect # $_: $DBI::errstr\n"));
  1012.     }
  1013.     print "\nDisconnecting...\n" if $verb;
  1014.     for (@cons) {
  1015.         $_->disconnect or warn "bad disconnect $DBI::errstr"
  1016.     }
  1017.     }
  1018.     my $t2 = new Benchmark;
  1019.     my $td = Benchmark::timediff($t2, $t1);
  1020.     printf "Made %2d connections in %s\n", $loops*$par, Benchmark::timestr($td);
  1021.     print "\n";
  1022.     return $td;
  1023. }
  1024.  
  1025.  
  1026. # Help people doing DBI->errstr, might even document it one day
  1027. # XXX probably best moved to cheaper XS code
  1028. sub err    { $DBI::err    }
  1029. sub errstr { $DBI::errstr }
  1030.  
  1031.  
  1032. # --- Private Internal Function for Creating New DBI Handles
  1033.  
  1034. sub _new_handle {
  1035.     my ($class, $parent, $attr, $imp_data, $imp_class) = @_;
  1036.  
  1037.     Carp::croak('Usage: DBI::_new_handle'
  1038.         .'($class_name, parent_handle, \%attr, $imp_data)'."\n"
  1039.         .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n")
  1040.     unless (@_ == 5    and (!$parent or ref $parent)
  1041.             and ref $attr eq 'HASH'
  1042.             and $imp_class);
  1043.  
  1044.     $attr->{ImplementorClass} = $imp_class
  1045.     or Carp::croak("_new_handle($class): 'ImplementorClass' attribute not given");
  1046.  
  1047.     DBI->trace_msg("    New $class (for $imp_class, parent=$parent, id=".($imp_data||'').")\n")
  1048.     if $DBI::dbi_debug >= 3;
  1049.  
  1050.     # This is how we create a DBI style Object:
  1051.     my (%hash, $i, $h);
  1052.     $i = tie    %hash, $class, $attr;  # ref to inner hash (for driver)
  1053.     $h = bless \%hash, $class;         # ref to outer hash (for application)
  1054.     # The above tie and bless may migrate down into _setup_handle()...
  1055.     # Now add magic so DBI method dispatch works
  1056.     DBI::_setup_handle($h, $imp_class, $parent, $imp_data);
  1057.  
  1058.     return $h unless wantarray;
  1059.     ($h, $i);
  1060. }
  1061. # XXX minimum constructors for the tie's (alias to XS version)
  1062. sub DBI::st::TIEHASH { bless $_[1] => $_[0] };
  1063. *DBI::dr::TIEHASH = \&DBI::st::TIEHASH;
  1064. *DBI::db::TIEHASH = \&DBI::st::TIEHASH;
  1065.  
  1066.  
  1067. # These three special constructors are called by the drivers
  1068. # The way they are called is likely to change.
  1069.  
  1070. my $profile;
  1071.  
  1072. sub _new_drh {    # called by DBD::<drivername>::driver()
  1073.     my ($class, $initial_attr, $imp_data) = @_;
  1074.     # Provide default storage for State,Err and Errstr.
  1075.     # Note that these are shared by all child handles by default! XXX
  1076.     # State must be undef to get automatic faking in DBI::var::FETCH
  1077.     my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, '');
  1078.     my $attr = {
  1079.     # these attributes get copied down to child handles by default
  1080.     'State'        => \$h_state_store,  # Holder for DBI::state
  1081.     'Err'        => \$h_err_store,    # Holder for DBI::err
  1082.     'Errstr'    => \$h_errstr_store, # Holder for DBI::errstr
  1083.     'TraceLevel'     => 0,
  1084.     FetchHashKeyName=> 'NAME',
  1085.     %$initial_attr,
  1086.     };
  1087.     my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class);
  1088.  
  1089.     # XXX DBI_PROFILE unless DBI::PurePerl because for some reason
  1090.     # it kills the t/zz_*_pp.t tests (they silently exit early)
  1091.     if ($ENV{DBI_PROFILE} && !$DBI::PurePerl) {
  1092.     # The profile object created here when the first driver is loaded
  1093.     # is shared by all drivers so we end up with just one set of profile
  1094.     # data and thus the 'total time in DBI' is really the true total.
  1095.     if (!$profile) {    # first time
  1096.         $h->{Profile} = $ENV{DBI_PROFILE};
  1097.         $profile = $h->{Profile};
  1098.     }
  1099.     else {
  1100.         $h->{Profile} = $profile;
  1101.     }
  1102.     }
  1103.     return $h unless wantarray;
  1104.     ($h, $i);
  1105. }
  1106.  
  1107. sub _new_dbh {    # called by DBD::<drivername>::dr::connect()
  1108.     my ($drh, $attr, $imp_data) = @_;
  1109.     my $imp_class = $drh->{ImplementorClass}
  1110.     or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass");
  1111.     substr($imp_class,-4,4) = '::db';
  1112.     my $app_class = ref $drh;
  1113.     substr($app_class,-4,4) = '::db';
  1114.     $attr->{Err}    ||= \my $err;
  1115.     $attr->{Errstr} ||= \my $errstr;
  1116.     $attr->{State}  ||= \my $state;
  1117.     _new_handle($app_class, $drh, $attr, $imp_data, $imp_class);
  1118. }
  1119.  
  1120. sub _new_sth {    # called by DBD::<drivername>::db::prepare)
  1121.     my ($dbh, $attr, $imp_data) = @_;
  1122.     my $imp_class = $dbh->{ImplementorClass}
  1123.     or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass");
  1124.     substr($imp_class,-4,4) = '::st';
  1125.     my $app_class = ref $dbh;
  1126.     substr($app_class,-4,4) = '::st';
  1127.     _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class);
  1128. }
  1129.  
  1130.  
  1131. # end of DBI package
  1132.  
  1133.  
  1134.  
  1135. # --------------------------------------------------------------------
  1136. # === The internal DBI Switch pseudo 'driver' class ===
  1137.  
  1138. {   package    # hide from PAUSE
  1139.     DBD::Switch::dr;
  1140.     DBI->setup_driver('DBD::Switch');    # sets up @ISA
  1141.  
  1142.     $DBD::Switch::dr::imp_data_size = 0;
  1143.     $DBD::Switch::dr::imp_data_size = 0;    # avoid typo warning
  1144.     my $drh;
  1145.  
  1146.     sub driver {
  1147.     return $drh if $drh;    # a package global
  1148.  
  1149.     my $inner;
  1150.     ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', {
  1151.         'Name'    => 'Switch',
  1152.         'Version' => $DBI::VERSION,
  1153.         'Attribution' => "DBI $DBI::VERSION by Tim Bunce",
  1154.         });
  1155.     Carp::croak("DBD::Switch init failed!") unless ($drh && $inner);
  1156.     return $drh;
  1157.     }
  1158.     sub CLONE {
  1159.     undef $drh;
  1160.     }
  1161.  
  1162.     sub FETCH {
  1163.     my($drh, $key) = @_;
  1164.     return DBI->trace if $key eq 'DebugDispatch';
  1165.     return undef if $key eq 'DebugLog';    # not worth fetching, sorry
  1166.     return $drh->DBD::_::dr::FETCH($key);
  1167.     undef;
  1168.     }
  1169.     sub STORE {
  1170.     my($drh, $key, $value) = @_;
  1171.     if ($key eq 'DebugDispatch') {
  1172.         DBI->trace($value);
  1173.     } elsif ($key eq 'DebugLog') {
  1174.         DBI->trace(-1, $value);
  1175.     } else {
  1176.         $drh->DBD::_::dr::STORE($key, $value);
  1177.     }
  1178.     }
  1179. }
  1180.  
  1181.  
  1182. # --------------------------------------------------------------------
  1183. # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES ===
  1184.  
  1185. # We only define default methods for harmless functions.
  1186. # We don't, for example, define a DBD::_::st::prepare()
  1187.  
  1188. {   package        # hide from PAUSE
  1189.     DBD::_::common; # ====== Common base class methods ======
  1190.     use strict;
  1191.  
  1192.     # methods common to all handle types:
  1193.  
  1194.     sub _not_impl {
  1195.     my ($h, $method) = @_;
  1196.     $h->trace_msg("Driver does not implement the $method method.\n");
  1197.     return;    # empty list / undef
  1198.     }
  1199.  
  1200.     # generic TIEHASH default methods:
  1201.     sub FIRSTKEY { }
  1202.     sub NEXTKEY  { }
  1203.     sub EXISTS   { defined($_[0]->FETCH($_[1])) } # XXX undef?
  1204.     sub CLEAR    { Carp::carp "Can't CLEAR $_[0] (DBI)" }
  1205.  
  1206.     *dump_handle = \&DBI::dump_handle;
  1207.  
  1208.     sub install_method {
  1209.     # special class method called directly by apps and/or drivers
  1210.     # to install new methods into the DBI dispatcher
  1211.     # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' });
  1212.     my ($class, $method, $attr) = @_;
  1213.     Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st")
  1214.         unless $class =~ /^DBD::(\w+)::(dr|db|st)$/;
  1215.     my ($driver, $subtype) = ($1, $2);
  1216.     Carp::croak("invalid method name '$method'")
  1217.         unless $method =~ m/^([a-z]+_)\w+$/;
  1218.     my $prefix = $1;
  1219.     my $reg_info = $dbd_prefix_registry->{$prefix};
  1220.     Carp::croak("method name prefix '$prefix' is not registered") unless $reg_info;
  1221.     my %attr = %{$attr||{}}; # copy so we can edit
  1222.     # XXX reformat $attr as needed for _install_method
  1223.     my ($caller_pkg, $filename, $line) = caller;
  1224.     DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr);
  1225.     }
  1226.  
  1227. }
  1228.  
  1229.  
  1230. {   package        # hide from PAUSE
  1231.     DBD::_::dr;    # ====== DRIVER ======
  1232.     @DBD::_::dr::ISA = qw(DBD::_::common);
  1233.     use strict;
  1234.  
  1235.     sub default_user {
  1236.     my ($drh, $user, $pass, $attr) = @_;
  1237.     unless (defined $user) {
  1238.         $user = $ENV{DBI_USER};
  1239.         Carp::carp("DBI connect: user not defined and DBI_USER env var not set")
  1240.         if 0 && !defined $user && $drh->{Warn};    # XXX enable later
  1241.     }
  1242.     unless (defined $pass) {
  1243.         $pass = $ENV{DBI_PASS};
  1244.         Carp::carp("DBI connect: password not defined and DBI_PASS env var not set")
  1245.         if 0 && !defined $pass && $drh->{Warn};    # XXX enable later
  1246.     }
  1247.     return ($user, $pass);
  1248.     }
  1249.  
  1250.     sub connect { # normally overridden, but a handy default
  1251.     my ($drh, $dsn, $user, $auth) = @_;
  1252.     my ($this) = DBI::_new_dbh($drh, {
  1253.         'Name' => $dsn,
  1254.     });
  1255.     $this;
  1256.     }
  1257.  
  1258.  
  1259.     sub connect_cached {
  1260.     my $drh = shift;
  1261.     my ($dsn, $user, $auth, $attr)= @_;
  1262.  
  1263.     # Needs support at dbh level to clear cache before complaining about
  1264.     # active children. The XS template code does this. Drivers not using
  1265.     # the template must handle clearing the cache themselves.
  1266.     my $cache = $drh->FETCH('CachedKids');
  1267.     $drh->STORE('CachedKids', $cache = {}) unless $cache;
  1268.  
  1269.     my @attr_keys = $attr ? sort keys %$attr : ();
  1270.     my $key = join "~~", $dsn, $user||'', $auth||'',
  1271.         $attr ? (@attr_keys,@{$attr}{@attr_keys}) : ();
  1272.     my $dbh = $cache->{$key};
  1273.     return $dbh if $dbh && $dbh->FETCH('Active') && eval { $dbh->ping };
  1274.     $dbh = $drh->connect(@_);
  1275.     $cache->{$key} = $dbh;    # replace prev entry, even if connect failed
  1276.     return $dbh;
  1277.     }
  1278.  
  1279. }
  1280.  
  1281.  
  1282. {   package        # hide from PAUSE
  1283.     DBD::_::db;    # ====== DATABASE ======
  1284.     @DBD::_::db::ISA = qw(DBD::_::common);
  1285.     use strict;
  1286.  
  1287.     sub clone {
  1288.     my ($old_dbh, $attr) = @_;
  1289.     my $closure = $old_dbh->{dbi_connect_closure} or return;
  1290.     unless ($attr) {
  1291.         # copy attributes visible in the attribute cache
  1292.         keys %$old_dbh;    # reset iterator
  1293.         while ( my ($k, $v) = each %$old_dbh ) {
  1294.         # ignore non-code refs, i.e., caches, handles, Err etc
  1295.         next if ref $v && ref $v ne 'CODE'; # HandleError etc
  1296.         $attr->{$k} = $v;
  1297.         }
  1298.         # explicitly set attributes which are unlikely to be in the
  1299.         # attribute cache, i.e., boolean's and some others
  1300.         $attr->{$_} = $old_dbh->FETCH($_) for (qw(
  1301.         AutoCommit ChopBlanks InactiveDestroy
  1302.         LongTruncOk PrintError Profile RaiseError
  1303.         ShowErrorStatement TaintIn TaintOut
  1304.         ));
  1305.     }
  1306.     # use Data::Dumper; warn Dumper([$old_dbh, $attr]);
  1307.     my $new_dbh = &$closure($old_dbh, $attr);
  1308.     unless ($new_dbh) {
  1309.         # need to copy err/errstr from driver back into $old_dbh
  1310.         my $drh = $old_dbh->{Driver};
  1311.         return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state);
  1312.     }
  1313.     return $new_dbh;
  1314.     }
  1315.  
  1316.     sub quote_identifier {
  1317.     my ($dbh, @id) = @_;
  1318.     my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef;
  1319.  
  1320.     my $info = $dbh->{dbi_quote_identifier_cache} ||= [
  1321.         $dbh->get_info(29)  || '"',    # SQL_IDENTIFIER_QUOTE_CHAR
  1322.         $dbh->get_info(41)  || '.',    # SQL_CATALOG_NAME_SEPARATOR
  1323.         $dbh->get_info(114) ||   1,    # SQL_CATALOG_LOCATION
  1324.     ];
  1325.  
  1326.     my $quote = $info->[0];
  1327.     foreach (@id) {            # quote the elements
  1328.         next unless defined;
  1329.         s/$quote/$quote$quote/g;    # escape embedded quotes
  1330.         $_ = qq{$quote$_$quote};
  1331.     }
  1332.  
  1333.     # strip out catalog if present for special handling
  1334.     my $catalog = (@id >= 3) ? shift @id : undef;
  1335.  
  1336.     # join the dots, ignoring any null/undef elements (ie schema)
  1337.     my $quoted_id = join '.', grep { defined } @id;
  1338.  
  1339.     if ($catalog) {            # add catalog correctly
  1340.         $quoted_id = ($info->[2] == 2)    # SQL_CL_END
  1341.             ? $quoted_id . $info->[1] . $catalog
  1342.             : $catalog   . $info->[1] . $quoted_id;
  1343.     }
  1344.     return $quoted_id;
  1345.     }
  1346.  
  1347.     sub quote {
  1348.     my ($dbh, $str, $data_type) = @_;
  1349.  
  1350.     return "NULL" unless defined $str;
  1351.     unless ($data_type) {
  1352.         $str =~ s/'/''/g;        # ISO SQL2
  1353.         return "'$str'";
  1354.     }
  1355.  
  1356.     my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ];
  1357.     my ($prefixes, $suffixes) = @$dbi_literal_quote_cache;
  1358.  
  1359.     my $lp = $prefixes->{$data_type};
  1360.     my $ls = $suffixes->{$data_type};
  1361.  
  1362.     if ( ! defined $lp || ! defined $ls ) {
  1363.         my $ti = $dbh->type_info($data_type);
  1364.         $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'";
  1365.         $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'";
  1366.     }
  1367.     return $str unless $lp || $ls; # no quoting required
  1368.  
  1369.     # XXX don't know what the standard says about escaping
  1370.     # in the 'general case' (where $lp != "'").
  1371.     # So we just do this and hope:
  1372.     $str =~ s/$lp/$lp$lp/g
  1373.         if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"');
  1374.     return "$lp$str$ls";
  1375.     }
  1376.  
  1377.     sub rows { -1 }    # here so $DBI::rows 'works' after using $dbh
  1378.  
  1379.     sub do {
  1380.     my($dbh, $statement, $attr, @params) = @_;
  1381.     my $sth = $dbh->prepare($statement, $attr) or return undef;
  1382.     $sth->execute(@params) or return undef;
  1383.     my $rows = $sth->rows;
  1384.     ($rows == 0) ? "0E0" : $rows;
  1385.     }
  1386.  
  1387.     sub _do_selectrow {
  1388.     my ($method, $dbh, $stmt, $attr, @bind) = @_;
  1389.     my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr))
  1390.         or return;
  1391.     $sth->execute(@bind)
  1392.         or return;
  1393.     my $row = $sth->$method()
  1394.         and $sth->finish;
  1395.     return $row;
  1396.     }
  1397.  
  1398.     sub selectrow_hashref {  return _do_selectrow('fetchrow_hashref',  @_); }
  1399.  
  1400.     # XXX selectrow_array/ref also have C implementations in Driver.xst
  1401.     sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); }
  1402.     sub selectrow_array {
  1403.     my $row = _do_selectrow('fetchrow_arrayref', @_) or return;
  1404.     return $row->[0] unless wantarray;
  1405.     return @$row;
  1406.     }
  1407.  
  1408.     # XXX selectall_arrayref also has C implementation in Driver.xst
  1409.     # which fallsback to this if a slice is given
  1410.     sub selectall_arrayref {
  1411.     my ($dbh, $stmt, $attr, @bind) = @_;
  1412.     my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)
  1413.         or return;
  1414.     $sth->execute(@bind) || return;
  1415.     my $slice = $attr->{Slice}; # typically undef, else hash or array ref
  1416.     if (!$slice and $slice=$attr->{Columns}) {
  1417.         if (ref $slice eq 'ARRAY') { # map col idx to perl array idx
  1418.         $slice = [ @{$attr->{Columns}} ];    # take a copy
  1419.         for (@$slice) { $_-- }
  1420.         }
  1421.     }
  1422.     return $sth->fetchall_arrayref($slice, $attr->{MaxRows});
  1423.     }
  1424.  
  1425.     sub selectall_hashref {
  1426.     my ($dbh, $stmt, $key_field, $attr, @bind) = @_;
  1427.     my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
  1428.     return unless $sth;
  1429.     $sth->execute(@bind) || return;
  1430.     return $sth->fetchall_hashref($key_field);
  1431.     }
  1432.  
  1433.     sub selectcol_arrayref {
  1434.     my ($dbh, $stmt, $attr, @bind) = @_;
  1435.     my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
  1436.     return unless $sth;
  1437.     $sth->execute(@bind) || return;
  1438.     my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1);
  1439.     my @values  = (undef) x @columns;
  1440.     my $idx = 0;
  1441.     for (@columns) {
  1442.         $sth->bind_col($_, \$values[$idx++]) || return;
  1443.     }
  1444.     my @col;
  1445.     if (my $max = $attr->{MaxRows}) {
  1446.         push @col, @values while @col<$max && $sth->fetch;
  1447.     }
  1448.     else {
  1449.         push @col, @values while $sth->fetch;
  1450.     }
  1451.     return \@col;
  1452.     }
  1453.  
  1454.     sub prepare_cached {
  1455.     my ($dbh, $statement, $attr, $allow_active) = @_;
  1456.     # Needs support at dbh level to clear cache before complaining about
  1457.     # active children. The XS template code does this. Drivers not using
  1458.     # the template must handle clearing the cache themselves.
  1459.     my $cache = $dbh->FETCH('CachedKids');
  1460.     $dbh->STORE('CachedKids', $cache = {}) unless $cache;
  1461.     my @attr_keys = ($attr) ? sort keys %$attr : ();
  1462.     my $key = ($attr) ? join("~~", $statement, @attr_keys, @{$attr}{@attr_keys}) : $statement;
  1463.     my $sth = $cache->{$key};
  1464.     if ($sth) {
  1465.         if ($sth->FETCH('Active') && ($allow_active||0) != 2) {
  1466.         Carp::carp("prepare_cached($statement) statement handle $sth was still active")
  1467.             if !$allow_active;
  1468.         $sth->finish;
  1469.         }
  1470.         return $sth;
  1471.     }
  1472.     $sth = $dbh->prepare($statement, $attr);
  1473.     $cache->{$key} = $sth if $sth;
  1474.     return $sth;
  1475.     }
  1476.  
  1477.     sub ping {
  1478.     shift->_not_impl('ping');
  1479.     "0 but true";    # special kind of true 0
  1480.     }
  1481.  
  1482.     sub begin_work {
  1483.     my $dbh = shift;
  1484.     return $dbh->DBI::set_err(1, "Already in a transaction")
  1485.         unless $dbh->FETCH('AutoCommit');
  1486.     $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it
  1487.     $dbh->STORE('BegunWork',  1); # trigger post commit/rollback action
  1488.     return 1;
  1489.     }
  1490.  
  1491.     sub primary_key {
  1492.     my ($dbh, @args) = @_;
  1493.     my $sth = $dbh->primary_key_info(@args) or return;
  1494.     my ($row, @col);
  1495.     push @col, $row->[3] while ($row = $sth->fetch);
  1496.     Carp::croak("primary_key method not called in list context")
  1497.         unless wantarray; # leave us some elbow room
  1498.     return @col;
  1499.     }
  1500.  
  1501.     sub tables {
  1502.     my ($dbh, @args) = @_;
  1503.     my $sth    = $dbh->table_info(@args) or return;
  1504.     my $tables = $sth->fetchall_arrayref or return;
  1505.     my @tables;
  1506.     if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR
  1507.         @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables;
  1508.     }
  1509.     else {        # temporary old style hack (yeach)
  1510.         @tables = map {
  1511.         my $name = $_->[2];
  1512.         if ($_->[1]) {
  1513.             my $schema = $_->[1];
  1514.             # a sad hack (mostly for Informix I recall)
  1515.             my $quote = ($schema eq uc($schema)) ? '' : '"';
  1516.             $name = "$quote$schema$quote.$name"
  1517.         }
  1518.         $name;
  1519.         } @$tables;
  1520.     }
  1521.     return @tables;
  1522.     }
  1523.  
  1524.     sub type_info {    # this should be sufficient for all drivers
  1525.     my ($dbh, $data_type) = @_;
  1526.     my $idx_hash;
  1527.     my $tia = $dbh->{dbi_type_info_row_cache};
  1528.     if ($tia) {
  1529.         $idx_hash = $dbh->{dbi_type_info_idx_cache};
  1530.     }
  1531.     else {
  1532.         my $temp = $dbh->type_info_all;
  1533.         return unless $temp && @$temp;
  1534.         # we cache here because type_info_all may be expensive to call
  1535.         $tia      = $dbh->{dbi_type_info_row_cache} = $temp;
  1536.         $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia;
  1537.     }
  1538.  
  1539.     my $dt_idx   = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type};
  1540.     Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)")
  1541.         if $dt_idx && $dt_idx != 1;
  1542.  
  1543.     # --- simple DATA_TYPE match filter
  1544.     my @ti;
  1545.     my @data_type_list = (ref $data_type) ? @$data_type : ($data_type);
  1546.     foreach $data_type (@data_type_list) {
  1547.         if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) {
  1548.         push @ti, grep { $_->[$dt_idx] == $data_type } @$tia;
  1549.         }
  1550.         else {    # SQL_ALL_TYPES
  1551.         push @ti, @$tia;
  1552.         }
  1553.         last if @ti;    # found at least one match
  1554.     }
  1555.  
  1556.     # --- format results into list of hash refs
  1557.     my $idx_fields = keys %$idx_hash;
  1558.     my @idx_names  = map { uc($_) } keys %$idx_hash;
  1559.     my @idx_values = values %$idx_hash;
  1560.     Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields"
  1561.         if @ti && @{$ti[0]} != $idx_fields;
  1562.     my @out = map {
  1563.         my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h;
  1564.     } @ti;
  1565.     return $out[0] unless wantarray;
  1566.     return @out;
  1567.     }
  1568.  
  1569.     sub data_sources {
  1570.     my ($dbh, @other) = @_;
  1571.     my $drh = $dbh->{Driver}; # XXX proxy issues?
  1572.     return $drh->data_sources(@other);
  1573.     }
  1574.  
  1575. }
  1576.  
  1577.  
  1578. {   package        # hide from PAUSE
  1579.     DBD::_::st;    # ====== STATEMENT ======
  1580.     @DBD::_::st::ISA = qw(DBD::_::common);
  1581.     use strict;
  1582.  
  1583.     sub bind_param { Carp::croak("Can't bind_param, not implement by driver") }
  1584.  
  1585. #
  1586. # ********************************************************
  1587. #
  1588. #    BEGIN ARRAY BINDING
  1589. #
  1590. #    Array binding support for drivers which don't support
  1591. #    array binding, but have sufficient interfaces to fake it.
  1592. #    NOTE: mixing scalars and arrayrefs requires using bind_param_array
  1593. #    for *all* params...unless we modify bind_param for the default
  1594. #    case...
  1595. #
  1596. #    2002-Apr-10    D. Arnold
  1597.  
  1598.     sub bind_param_array {
  1599.     my $sth = shift;
  1600.     my ($p_id, $value_array, $attr) = @_;
  1601.  
  1602.     return $sth->DBI::set_err(1, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array))
  1603.         if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY';
  1604.  
  1605.     return $sth->DBI::set_err(1, "Can't use named placeholders for non-driver supported bind_param_array")
  1606.         unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here
  1607.  
  1608.     # get/create arrayref to hold params
  1609.     my $hash_of_arrays = $sth->{ParamArrays} ||= { };
  1610.  
  1611.     if (ref $value_array eq 'ARRAY') {
  1612.         # check that input has same length as existing
  1613.         # find first arrayref entry (if any)
  1614.         foreach (keys %$hash_of_arrays) {
  1615.         my $v = $$hash_of_arrays{$_};
  1616.         next unless ref $v eq 'ARRAY';
  1617.         return $sth->DBI::set_err(1,
  1618.             "Arrayref for parameter $p_id has ".@$value_array." elements"
  1619.             ." but parameter $_ has ".@$v)
  1620.             if @$value_array != @$v;
  1621.         }
  1622.     }
  1623.  
  1624.     # If the bind has attribs then we rely on the driver conforming to
  1625.     # the DBI spec in that a single bind_param() call with those attribs
  1626.     # makes them 'sticky' and apply to all later execute(@values) calls.
  1627.     # Since we only call bind_param() if we're given attribs then
  1628.     # applications using drivers that don't support bind_param can still
  1629.     # use bind_param_array() so long as they don't pass any attribs.
  1630.  
  1631.     $$hash_of_arrays{$p_id} = $value_array;
  1632.     return $sth->bind_param($p_id, undef, $attr) 
  1633.         if $attr;
  1634.     1;
  1635.     }
  1636.  
  1637.     sub bind_param_inout_array { 
  1638.     my $sth = shift;
  1639.     # XXX not supported so we just call bind_param_array instead
  1640.     # and then return an error
  1641.     my ($p_num, $value_array, $attr) = @_;
  1642.     $sth->bind_param_array($p_num, $value_array, $attr);
  1643.     return $sth->DBI::set_err(1, "bind_param_inout_array not supported");
  1644.     }
  1645.  
  1646.     sub execute_array {
  1647.     my $sth = shift;
  1648.     my ($attr, @array_of_arrays) = @_;
  1649.     my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point
  1650.  
  1651.     # get tuple status array or hash attribute
  1652.     my $tuple_sts = $attr->{ArrayTupleStatus};
  1653.     return $sth->DBI::set_err(1, "ArrayTupleStatus attribute must be an arrayref")
  1654.         if $tuple_sts and ref $tuple_sts ne 'ARRAY';
  1655.  
  1656.     # bind all supplied arrays
  1657.     if (@array_of_arrays) {
  1658.         $sth->{ParamArrays} = { };    # clear out old params
  1659.         return $sth->DBI::set_err(1,
  1660.             @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected")
  1661.         if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS;
  1662.         $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return
  1663.         foreach (1..@array_of_arrays);
  1664.     }
  1665.  
  1666.     my $fetch_tuple_sub;
  1667.  
  1668.     if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) {    # fetch on demand
  1669.  
  1670.         return $sth->DBI::set_err(1,
  1671.             "Can't use both ArrayTupleFetch and explicit bind values")
  1672.         if @array_of_arrays; # previous bind_param_array calls will simply be ignored
  1673.  
  1674.         if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) {
  1675.         my $fetch_sth = $fetch_tuple_sub;
  1676.         return $sth->DBI::set_err(1,
  1677.             "ArrayTupleFetch sth is not Active, need to execute() it first")
  1678.             unless $fetch_sth->{Active};
  1679.         # check column count match to give more friendly message
  1680.         my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS};
  1681.         return $sth->DBI::set_err(1,
  1682.             "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected")
  1683.             if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS)
  1684.             && $NUM_OF_FIELDS != $NUM_OF_PARAMS;
  1685.         $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref };
  1686.         }
  1687.         elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) {
  1688.         return $sth->DBI::set_err(1, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle");
  1689.         }
  1690.  
  1691.     }
  1692.     else {
  1693.         my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} };
  1694.         return $sth->DBI::set_err(1,
  1695.             "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected")
  1696.         if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given;
  1697.  
  1698.         # get the length of a bound array
  1699.         my $len = 1; # in case all are scalars
  1700.         my %hash_of_arrays = %{$sth->{ParamArrays}};
  1701.         foreach (keys(%hash_of_arrays)) {
  1702.         my $ary = $hash_of_arrays{$_};
  1703.         $len = @$ary if ref $ary eq 'ARRAY';
  1704.         }
  1705.         my @bind_ids = 1..keys(%hash_of_arrays);
  1706.  
  1707.         my $tuple_idx = 0;
  1708.         $fetch_tuple_sub = sub {
  1709.         return if $tuple_idx >= $len;
  1710.         my @tuple = map {
  1711.             my $a = $hash_of_arrays{$_};
  1712.             ref($a) ? $a->[$tuple_idx] : $a
  1713.         } @bind_ids;
  1714.         ++$tuple_idx;
  1715.         return \@tuple;
  1716.         };
  1717.     }
  1718.  
  1719.     return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts);
  1720.     }
  1721.  
  1722.     sub execute_for_fetch {
  1723.     my ($sth, $fetch_tuple_sub, $tuple_status) = @_;
  1724.     @$tuple_status = () if $tuple_status; # reset the status array
  1725.  
  1726.     my ($err_count, %errstr_cache);
  1727.     while ( my $tuple = &$fetch_tuple_sub() ) {
  1728.         if ( my $rc = $sth->execute(@$tuple) ) {
  1729.         push @$tuple_status, $rc;
  1730.         }
  1731.         else {
  1732.         $err_count++;
  1733.         my $err = $sth->err;
  1734.         push @$tuple_status, [ $err, $errstr_cache{$err} ||= $sth->errstr, $sth->state ];
  1735.         }
  1736.     }
  1737.     return ($err_count) ? undef : scalar @$tuple_status;
  1738.     }
  1739.  
  1740.  
  1741.     sub fetchall_arrayref {    # ALSO IN Driver.xst
  1742.     my ($sth, $slice, $max_rows) = @_;
  1743.     $max_rows = -1 unless defined $max_rows;
  1744.     my $mode = ref($slice) || 'ARRAY';
  1745.     my @rows;
  1746.     my $row;
  1747.     if ($mode eq 'ARRAY') {
  1748.         # we copy the array here because fetch (currently) always
  1749.         # returns the same array ref. XXX
  1750.         if ($slice && @$slice) {
  1751.         $max_rows = -1 unless defined $max_rows;
  1752.         push @rows, [ @{$row}[ @$slice] ]
  1753.             while($max_rows-- and $row = $sth->fetch);
  1754.         }
  1755.         elsif (defined $max_rows) {
  1756.         $max_rows = -1 unless defined $max_rows;
  1757.         push @rows, [ @$row ]
  1758.             while($max_rows-- and $row = $sth->fetch);
  1759.         }
  1760.         else {
  1761.         push @rows, [ @$row ]          while($row = $sth->fetch);
  1762.         }
  1763.     }
  1764.     elsif ($mode eq 'HASH') {
  1765.         $max_rows = -1 unless defined $max_rows;
  1766.         if (keys %$slice) {
  1767.         my @o_keys = keys %$slice;
  1768.         my @i_keys = map { lc } keys %$slice;
  1769.         while ($max_rows-- and $row = $sth->fetchrow_hashref('NAME_lc')) {
  1770.             my %hash;
  1771.             @hash{@o_keys} = @{$row}{@i_keys};
  1772.             push @rows, \%hash;
  1773.         }
  1774.         }
  1775.         else {
  1776.         # XXX assumes new ref each fetchhash
  1777.         push @rows, $row
  1778.             while ($max_rows-- and $row = $sth->fetchrow_hashref());
  1779.         }
  1780.     }
  1781.     else { Carp::croak("fetchall_arrayref($mode) invalid") }
  1782.     return \@rows;
  1783.     }
  1784.  
  1785.     sub fetchall_hashref {    # XXX may be better to fetchall_arrayref then convert to hashes
  1786.     my ($sth, $key_field) = @_;
  1787.  
  1788.     my $hash_key_name = $sth->{FetchHashKeyName};
  1789.     my $names_hash = $sth->FETCH("${hash_key_name}_hash");
  1790.     my $index = $names_hash->{$key_field};    # perl index not column number
  1791.     ++$index if defined $index;        # convert to column number
  1792.     $index ||= $key_field if DBI::looks_like_number($key_field) && $key_field>=1;
  1793.     return $sth->DBI::set_err(1, "Field '$key_field' does not exist (not one of @{[keys %$names_hash]})")
  1794.         unless defined $index;
  1795.     my $key_value;
  1796.     $sth->bind_col($index, \$key_value) or return;
  1797.     my %rows;
  1798.     while (my $row = $sth->fetchrow_hashref($hash_key_name)) {
  1799.         $rows{ $key_value } = $row;
  1800.     }
  1801.     return \%rows;
  1802.     }
  1803.  
  1804.     *dump_results = \&DBI::dump_results;
  1805.  
  1806.     sub blob_copy_to_file {    # returns length or undef on error
  1807.     my($self, $field, $filename_or_handleref, $blocksize) = @_;
  1808.     my $fh = $filename_or_handleref;
  1809.     my($len, $buf) = (0, "");
  1810.     $blocksize ||= 512;    # not too ambitious
  1811.     local(*FH);
  1812.     unless(ref $fh) {
  1813.         open(FH, ">$fh") || return undef;
  1814.         $fh = \*FH;
  1815.     }
  1816.     while(defined($self->blob_read($field, $len, $blocksize, \$buf))) {
  1817.         print $fh $buf;
  1818.         $len += length $buf;
  1819.     }
  1820.     close(FH);
  1821.     $len;
  1822.     }
  1823.  
  1824.     sub more_results {
  1825.     shift->{syb_more_results};    # handy grandfathering
  1826.     }
  1827.  
  1828. }
  1829.  
  1830. unless ($DBI::PurePerl) {   # See install_driver
  1831.     { @DBD::_mem::dr::ISA = qw(DBD::_mem::common);    }
  1832.     { @DBD::_mem::db::ISA = qw(DBD::_mem::common);    }
  1833.     { @DBD::_mem::st::ISA = qw(DBD::_mem::common);    }
  1834.     # DBD::_mem::common::DESTROY is implemented in DBI.xs
  1835. }
  1836.  
  1837. 1;
  1838. __END__
  1839.  
  1840. =head1 DESCRIPTION
  1841.  
  1842. The DBI is a database access module for the Perl programming language.  It defines
  1843. a set of methods, variables, and conventions that provide a consistent
  1844. database interface, independent of the actual database being used.
  1845.  
  1846. It is important to remember that the DBI is just an interface.
  1847. The DBI is a layer
  1848. of "glue" between an application and one or more database I<driver>
  1849. modules.  It is the driver modules which do most of the real work. The DBI
  1850. provides a standard interface and framework for the drivers to operate
  1851. within.
  1852.  
  1853.  
  1854. =head2 Architecture of a DBI Application
  1855.  
  1856.              |<- Scope of DBI ->|
  1857.                   .-.   .--------------.   .-------------.
  1858.   .-------.       | |---| XYZ Driver   |---| XYZ Engine  |
  1859.   | Perl  |       | |   `--------------'   `-------------'
  1860.   | script|  |A|  |D|   .--------------.   .-------------.
  1861.   | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
  1862.   | DBI   |  |I|  |I|   `--------------'   `-------------'
  1863.   | API   |       | |...
  1864.   |methods|       | |... Other drivers
  1865.   `-------'       | |...
  1866.                   `-'
  1867.  
  1868. The API, or Application Programming Interface, defines the
  1869. call interface and variables for Perl scripts to use. The API
  1870. is implemented by the Perl DBI extension.
  1871.  
  1872. The DBI "dispatches" the method calls to the appropriate driver for
  1873. actual execution.  The DBI is also responsible for the dynamic loading
  1874. of drivers, error checking and handling, providing default
  1875. implementations for methods, and many other non-database specific duties.
  1876.  
  1877. Each driver
  1878. contains implementations of the DBI methods using the
  1879. private interface functions of the corresponding database engine.  Only authors
  1880. of sophisticated/multi-database applications or generic library
  1881. functions need be concerned with drivers.
  1882.  
  1883. =head2 Notation and Conventions
  1884.  
  1885. The following conventions are used in this document:
  1886.  
  1887.   $dbh    Database handle object
  1888.   $sth    Statement handle object
  1889.   $drh    Driver handle object (rarely seen or used in applications)
  1890.   $h      Any of the handle types above ($dbh, $sth, or $drh)
  1891.   $rc     General Return Code  (boolean: true=ok, false=error)
  1892.   $rv     General Return Value (typically an integer)
  1893.   @ary    List of values returned from the database, typically a row of data
  1894.   $rows   Number of rows processed (if available, else -1)
  1895.   $fh     A filehandle
  1896.   undef   NULL values are represented by undefined values in Perl
  1897.   \%attr  Reference to a hash of attribute values passed to methods
  1898.  
  1899. Note that Perl will automatically destroy database and statement handle objects
  1900. if all references to them are deleted.
  1901.  
  1902.  
  1903. =head2 Outline Usage
  1904.  
  1905. To use DBI,
  1906. first you need to load the DBI module:
  1907.  
  1908.   use DBI;
  1909.   use strict;
  1910.  
  1911. (The C<use strict;> isn't required but is strongly recommended.)
  1912.  
  1913. Then you need to L</connect> to your data source and get a I<handle> for that
  1914. connection:
  1915.  
  1916.   $dbh = DBI->connect($dsn, $user, $password,
  1917.                       { RaiseError => 1, AutoCommit => 0 });
  1918.  
  1919. Since connecting can be expensive, you generally just connect at the
  1920. start of your program and disconnect at the end.
  1921.  
  1922. Explicitly defining the required C<AutoCommit> behaviour is strongly
  1923. recommended and may become mandatory in a later version.  This
  1924. determines whether changes are automatically committed to the
  1925. database when executed, or need to be explicitly committed later.
  1926.  
  1927. The DBI allows an application to "prepare" statements for later
  1928. execution.  A prepared statement is identified by a statement handle
  1929. held in a Perl variable.
  1930. We'll call the Perl variable C<$sth> in our examples.
  1931.  
  1932. The typical method call sequence for a C<SELECT> statement is:
  1933.  
  1934.   prepare,
  1935.     execute, fetch, fetch, ...
  1936.     execute, fetch, fetch, ...
  1937.     execute, fetch, fetch, ...
  1938.  
  1939. for example:
  1940.  
  1941.   $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
  1942.  
  1943.   $sth->execute( $baz );
  1944.  
  1945.   while ( @row = $sth->fetchrow_array ) {
  1946.     print "@row\n";
  1947.   }
  1948.  
  1949. The typical method call sequence for a I<non>-C<SELECT> statement is:
  1950.  
  1951.   prepare,
  1952.     execute,
  1953.     execute,
  1954.     execute.
  1955.  
  1956. for example:
  1957.  
  1958.   $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
  1959.  
  1960.   while(<CSV>) {
  1961.     chomp;
  1962.     my ($foo,$bar,$baz) = split /,/;
  1963.     $sth->execute( $foo, $bar, $baz );
  1964.   }
  1965.  
  1966. The C<do()> method can be used for non repeated I<non>-C<SELECT> statement
  1967. (or with drivers that don't support placeholders):
  1968.  
  1969.   $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
  1970.  
  1971. To commit your changes to the database (when L</AutoCommit> is off):
  1972.  
  1973.   $dbh->commit;  # or call $dbh->rollback; to undo changes
  1974.  
  1975. Finally, when you have finished working with the data source, you should
  1976. L</disconnect> from it:
  1977.  
  1978.   $dbh->disconnect;
  1979.  
  1980.  
  1981. =head2 General Interface Rules & Caveats
  1982.  
  1983. The DBI does not have a concept of a "current session". Every session
  1984. has a handle object (i.e., a C<$dbh>) returned from the C<connect> method.
  1985. That handle object is used to invoke database related methods.
  1986.  
  1987. Most data is returned to the Perl script as strings. (Null values are
  1988. returned as C<undef>.)  This allows arbitrary precision numeric data to be
  1989. handled without loss of accuracy.  Beware that Perl may not preserve
  1990. the same accuracy when the string is used as a number.
  1991.  
  1992. Dates and times are returned as character strings in the current
  1993. default format of the corresponding database engine.  Time zone effects
  1994. are database/driver dependent.
  1995.  
  1996. Perl supports binary data in Perl strings, and the DBI will pass binary
  1997. data to and from the driver without change. It is up to the driver
  1998. implementors to decide how they wish to handle such binary data.
  1999.  
  2000. Most databases that understand multiple character sets have a
  2001. default global charset. Text stored in the database is, or should
  2002. be, stored in that charset; if not, then that's the fault of either
  2003. the database or the application that inserted the data. When text is
  2004. fetched it should be automatically converted to the charset of the
  2005. client, presumably based on the locale. If a driver needs to set a
  2006. flag to get that behaviour, then it should do so; it should not require
  2007. the application to do that.
  2008.  
  2009. Multiple SQL statements may not be combined in a single statement
  2010. handle (C<$sth>), although some databases and drivers do support this
  2011. (notably Sybase and SQL Server).
  2012.  
  2013. Non-sequential record reads are not supported in this version of the DBI.
  2014. In other words, records can only be fetched in the order that the
  2015. database returned them, and once fetched they are forgotten.
  2016.  
  2017. Positioned updates and deletes are not directly supported by the DBI.
  2018. See the description of the C<CursorName> attribute for an alternative.
  2019.  
  2020. Individual driver implementors are free to provide any private
  2021. functions and/or handle attributes that they feel are useful.
  2022. Private driver functions can be invoked using the DBI C<func()> method.
  2023. Private driver attributes are accessed just like standard attributes.
  2024.  
  2025. Many methods have an optional C<\%attr> parameter which can be used to
  2026. pass information to the driver implementing the method. Except where
  2027. specifically documented, the C<\%attr> parameter can only be used to pass
  2028. driver specific hints. In general, you can ignore C<\%attr> parameters
  2029. or pass it as C<undef>.
  2030.  
  2031.  
  2032. =head2 Naming Conventions and Name Space
  2033.  
  2034. The DBI package and all packages below it (C<DBI::*>) are reserved for
  2035. use by the DBI. Extensions and related modules use the C<DBIx::>
  2036. namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>).
  2037. Package names beginning with C<DBD::> are reserved for use
  2038. by DBI database drivers.  All environment variables used by the DBI
  2039. or by individual DBDs begin with "C<DBI_>" or "C<DBD_>".
  2040.  
  2041. The letter case used for attribute names is significant and plays an
  2042. important part in the portability of DBI scripts.  The case of the
  2043. attribute name is used to signify who defined the meaning of that name
  2044. and its values.
  2045.  
  2046.   Case of name  Has a meaning defined by
  2047.   ------------  ------------------------
  2048.   UPPER_CASE    Standards, e.g.,  X/Open, ISO SQL92 etc (portable)
  2049.   MixedCase     DBI API (portable), underscores are not used.
  2050.   lower_case    Driver or database engine specific (non-portable)
  2051.  
  2052. It is of the utmost importance that Driver developers only use
  2053. lowercase attribute names when defining private attributes. Private
  2054. attribute names must be prefixed with the driver name or suitable
  2055. abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc).
  2056.  
  2057.  
  2058. =head2 SQL - A Query Language
  2059.  
  2060. Most DBI drivers require applications to use a dialect of SQL
  2061. (Structured Query Language) to interact with the database engine.
  2062. The L</"SQL Standards Reference Information"> section provides links
  2063. to useful information about SQL.
  2064.  
  2065. The DBI itself does not mandate or require any particular language to
  2066. be used; it is language independent. In ODBC terms, the DBI is in
  2067. "pass-thru" mode, although individual drivers might not be. The only requirement
  2068. is that queries and other statements must be expressed as a single
  2069. string of characters passed as the first argument to the L</prepare> or
  2070. L</do> methods.
  2071.  
  2072. For an interesting diversion on the I<real> history of RDBMS and SQL,
  2073. from the people who made it happen, see:
  2074.  
  2075.   http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html
  2076.  
  2077. Follow the "Full Contents" then "Intergalactic dataspeak" links for the
  2078. SQL history.
  2079.  
  2080. =head2 Placeholders and Bind Values
  2081.  
  2082. Some drivers support placeholders and bind values.
  2083. I<Placeholders>, also called parameter markers, are used to indicate
  2084. values in a database statement that will be supplied later,
  2085. before the prepared statement is executed.  For example, an application
  2086. might use the following to insert a row of data into the SALES table:
  2087.  
  2088.   INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
  2089.  
  2090. or the following, to select the description for a product:
  2091.  
  2092.   SELECT description FROM products WHERE product_code = ?
  2093.  
  2094. The C<?> characters are the placeholders.  The association of actual
  2095. values with placeholders is known as I<binding>, and the values are
  2096. referred to as I<bind values>.
  2097.  
  2098. Note that the C<?> is not enclosed in quotation marks, even when the
  2099. placeholder represents a string.  Some drivers also allow placeholders
  2100. like C<:>I<name> and C<:>I<n> (e.g., C<:1>, C<:2>, and so on)
  2101. in addition to C<?>, but their use is not portable.
  2102.  
  2103. With most drivers, placeholders can't be used for any element of a
  2104. statement that would prevent the database server from validating the
  2105. statement and creating a query execution plan for it. For example:
  2106.  
  2107.   "SELECT name, age FROM ?"         # wrong (will probably fail)
  2108.   "SELECT name, ?   FROM people"    # wrong (but may not 'fail')
  2109.  
  2110. Also, placeholders can only represent single scalar values.
  2111. For example, the following
  2112. statement won't work as expected for more than one value:
  2113.  
  2114.   "SELECT name, age FROM people WHERE name IN (?)"    # wrong
  2115.   "SELECT name, age FROM people WHERE name IN (?,?)"  # two names
  2116.  
  2117. When using placeholders with the SQL C<LIKE> qualifier, you must
  2118. remember that the placeholder substitutes for the whole string.
  2119. So you should use "C<... LIKE ? ...>" and include any wildcard
  2120. characters in the value that you bind to the placeholder.
  2121.  
  2122. B<Null Values>
  2123.  
  2124. Undefined values, or C<undef>, can be used to indicate null values.
  2125. However, care must be taken in the particular case of trying to use
  2126. null values to qualify a C<SELECT> statement. Consider:
  2127.  
  2128.   SELECT description FROM products WHERE product_code = ?
  2129.  
  2130. Binding an C<undef> (NULL) to the placeholder will I<not> select rows
  2131. which have a NULL C<product_code>! Refer to the SQL manual for your database
  2132. engine or any SQL book for the reasons for this.  To explicitly select
  2133. NULLs you have to say "C<WHERE product_code IS NULL>" and to make that
  2134. general you have to say:
  2135.  
  2136.   ... WHERE (product_code = ? OR (? IS NULL AND product_code IS NULL))
  2137.  
  2138. and bind the same value to both placeholders. Sadly, that more general
  2139. syntax doesn't work for Sybase and MS SQL Server. However on those two
  2140. servers the original "C<product_code = ?>" syntax works for binding nulls.
  2141.  
  2142. B<Performance>
  2143.  
  2144. Without using placeholders, the insert statement shown previously would have to
  2145. contain the literal values to be inserted and would have to be
  2146. re-prepared and re-executed for each row. With placeholders, the insert
  2147. statement only needs to be prepared once. The bind values for each row
  2148. can be given to the C<execute> method each time it's called. By avoiding
  2149. the need to re-prepare the statement for each row, the application
  2150. typically runs many times faster. Here's an example:
  2151.  
  2152.   my $sth = $dbh->prepare(q{
  2153.     INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
  2154.   }) or die $dbh->errstr;
  2155.   while (<>) {
  2156.       chomp;
  2157.       my ($product_code, $qty, $price) = split /,/;
  2158.       $sth->execute($product_code, $qty, $price) or die $dbh->errstr;
  2159.   }
  2160.   $dbh->commit or die $dbh->errstr;
  2161.  
  2162. See L</execute> and L</bind_param> for more details.
  2163.  
  2164. The C<q{...}> style quoting used in this example avoids clashing with
  2165. quotes that may be used in the SQL statement. Use the double-quote like
  2166. C<qq{...}> operator if you want to interpolate variables into the string.
  2167. See L<perlop/"Quote and Quote-like Operators"> for more details.
  2168.  
  2169. See also the L</bind_column> method, which is used to associate Perl
  2170. variables with the output columns of a C<SELECT> statement.
  2171.  
  2172. =head1 THE DBI PACKAGE AND CLASS
  2173.  
  2174. In this section, we cover the DBI class methods, utility functions,
  2175. and the dynamic attributes associated with generic DBI handles.
  2176.  
  2177. =head2 DBI Constants
  2178.  
  2179. Constants representing the values of the SQL standard types can be
  2180. imported individually by name, or all together by importing the
  2181. special C<:sql_types> tag.
  2182.  
  2183. The names and values of all the defined SQL standard types can be
  2184. produced like this:
  2185.  
  2186.   foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) {
  2187.     printf "%s=%d\n", $_, &{"DBI::$_"};
  2188.   }
  2189.  
  2190. These constants are defined by SQL/CLI, ODBC or both.
  2191. C<SQL_BIGINT> is (currently) omitted, because SQL/CLI and ODBC provide
  2192. conflicting codes.
  2193.  
  2194. See the L</type_info>, L</type_info_all>, and L</bind_param> methods
  2195. for possible uses.
  2196.  
  2197. Note that just because the DBI defines a named constant for a given
  2198. data type doesn't mean that drivers will support that data type.
  2199.  
  2200.  
  2201. =head2 DBI Class Methods
  2202.  
  2203. The following methods are provided by the DBI class:
  2204.  
  2205. =over 4
  2206.  
  2207. =item C<connect>
  2208.  
  2209.   $dbh = DBI->connect($data_source, $username, $password)
  2210.             or die $DBI::errstr;
  2211.   $dbh = DBI->connect($data_source, $username, $password, \%attr)
  2212.             or die $DBI::errstr;
  2213.  
  2214. Establishes a database connection, or session, to the requested C<$data_source>.
  2215. Returns a database handle object if the connection succeeds. Use
  2216. C<$dbh-E<gt>disconnect> to terminate the connection.
  2217.  
  2218. If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err>
  2219. and C<$DBI::errstr>. (It does I<not> set C<$!>, etc.) You should generally
  2220. test the return status of C<connect> and C<print $DBI::errstr> if it has failed.
  2221.  
  2222. Multiple simultaneous connections to multiple databases through multiple
  2223. drivers can be made via the DBI. Simply make one C<connect> call for each
  2224. database and keep a copy of each returned database handle.
  2225.  
  2226. The C<$data_source> value must begin with "C<dbi:>I<driver_name>C<:>".
  2227. The I<driver_name> specifies the driver that will be used to make the
  2228. connection. (Letter case is significant.)
  2229.  
  2230. As a convenience, if the C<$data_source> parameter is undefined or empty,
  2231. the DBI will substitute the value of the environment variable C<DBI_DSN>.
  2232. If just the I<driver_name> part is empty (i.e., the C<$data_source>
  2233. prefix is "C<dbi::>"), the environment variable C<DBI_DRIVER> is
  2234. used. If neither variable is set, then C<connect> dies.
  2235.  
  2236. Examples of C<$data_source> values are:
  2237.  
  2238.   dbi:DriverName:database_name
  2239.   dbi:DriverName:database_name@hostname:port
  2240.   dbi:DriverName:database=database_name;host=hostname;port=port
  2241.  
  2242. There is I<no standard> for the text following the driver name. Each
  2243. driver is free to use whatever syntax it wants. The only requirement the
  2244. DBI makes is that all the information is supplied in a single string.
  2245. You must consult the documentation for the drivers you are using for a
  2246. description of the syntax they require. (Where a driver author needs
  2247. to define a syntax for the C<$data_source>, it is recommended that
  2248. they follow the ODBC style, shown in the last example above.)
  2249.  
  2250. If the environment variable C<DBI_AUTOPROXY> is defined (and the
  2251. driver in C<$data_source> is not "C<Proxy>") then the connect request
  2252. will automatically be changed to:
  2253.  
  2254.   $ENV{DBI_AUTOPROXY};dsn=$data_source
  2255.  
  2256. C<DBI_AUTOPROXY> is typically set as "C<dbi:Proxy:hostname=...;port=...>".
  2257. If $ENV{DBI_AUTOPROXY} doesn't begin with 'C<dbi:>' then "dbi:Proxy:"
  2258. will be prepended to it first.  See the DBD::Proxy documentation
  2259. for more details.
  2260.  
  2261. If C<$username> or C<$password> are undefined (rather than just empty),
  2262. then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS>
  2263. environment variables, respectively.  The DBI will warn if the
  2264. environment variables are not defined.  However, the everyday use
  2265. of these environment variables is not recommended for security
  2266. reasons. The mechanism is primarily intended to simplify testing.
  2267. See below for alternative way to specify the username and password.
  2268.  
  2269. C<DBI-E<gt>connect> automatically installs the driver if it has not been
  2270. installed yet. Driver installation either returns a valid driver
  2271. handle, or it I<dies> with an error message that includes the string
  2272. "C<install_driver>" and the underlying problem. So C<DBI-E<gt>connect>
  2273. will die
  2274. on a driver installation failure and will only return C<undef> on a
  2275. connect failure, in which case C<$DBI::errstr> will hold the error message.
  2276.  
  2277. The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the
  2278. C<$username> and C<$password> arguments are then passed to the driver for
  2279. processing. The DBI does not define any interpretation for the
  2280. contents of these fields.  The driver is free to interpret the
  2281. C<$data_source>, C<$username>, and C<$password> fields in any way, and supply
  2282. whatever defaults are appropriate for the engine being accessed.
  2283. (Oracle, for example, uses the ORACLE_SID and TWO_TASK environment
  2284. variables if no C<$data_source> is specified.)
  2285.  
  2286. The C<AutoCommit> and C<PrintError> attributes for each connection default to
  2287. "on". (See L</AutoCommit> and L</PrintError> for more information.)
  2288. However, it is strongly recommended that you explicitly define C<AutoCommit>
  2289. rather than rely on the default. Future versions of
  2290. the DBI may issue a warning if C<AutoCommit> is not explicitly defined.
  2291.  
  2292. The C<\%attr> parameter can be used to alter the default settings of
  2293. C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example:
  2294.  
  2295.   $dbh = DBI->connect($data_source, $user, $pass, {
  2296.     PrintError => 0,
  2297.     AutoCommit => 0
  2298.   });
  2299.  
  2300. The username and password can also be specified using the attributes
  2301. C<Username> and C<Password>, in which case they take precedence
  2302. over the C<$username> and C<$password> parameters.
  2303.  
  2304. You can also define connection attribute values within the C<$data_source>
  2305. parameter. For example:
  2306.  
  2307.   dbi:DriverName(PrintError=>0,Taint=>1):...
  2308.  
  2309. Individual attributes values specified in this way take precedence over
  2310. any conflicting values specified via the C<\%attr> parameter to C<connect>.
  2311.  
  2312. The C<dbi_connect_method> attribute can be used to specify which driver
  2313. method should be called to establish the connection. The only useful
  2314. values are 'connect', 'connect_cached', or some specialized case like
  2315. 'Apache::DBI::connect' (which is automatically the default when running
  2316. within Apache).
  2317.  
  2318. Where possible, each session (C<$dbh>) is independent from the transactions
  2319. in other sessions. This is useful when you need to hold cursors open
  2320. across transactions--for example, if you use one session for your long lifespan
  2321. cursors (typically read-only) and another for your short update
  2322. transactions.
  2323.  
  2324. For compatibility with old DBI scripts, the driver can be specified by
  2325. passing its name as the fourth argument to C<connect> (instead of C<\%attr>):
  2326.  
  2327.   $dbh = DBI->connect($data_source, $user, $pass, $driver);
  2328.  
  2329. In this "old-style" form of C<connect>, the C<$data_source> should not start
  2330. with "C<dbi:driver_name:>". (If it does, the embedded driver_name
  2331. will be ignored). Also note that in this older form of C<connect>,
  2332. the C<$dbh-E<gt>{AutoCommit}> attribute is I<undefined>, the
  2333. C<$dbh-E<gt>{PrintError}> attribute is off, and the old C<DBI_DBNAME>
  2334. environment variable is
  2335. checked if C<DBI_DSN> is not defined. Beware that this "old-style"
  2336. C<connect> will be withdrawn in a future version of DBI.
  2337.  
  2338. =item C<connect_cached>
  2339.  
  2340.   $dbh = DBI->connect_cached($data_source, $username, $password)
  2341.             or die $DBI::errstr;
  2342.   $dbh = DBI->connect_cached($data_source, $username, $password, \%attr)
  2343.             or die $DBI::errstr;
  2344.  
  2345. C<connect_cached> is like L</connect>, except that the database handle
  2346. returned is also
  2347. stored in a hash associated with the given parameters. If another call
  2348. is made to C<connect_cached> with the same parameter values, then the
  2349. corresponding cached C<$dbh> will be returned if it is still valid.
  2350. The cached database handle is replaced with a new connection if it
  2351. has been disconnected or if the C<ping> method fails.
  2352.  
  2353. Note that the behaviour of this method differs in several respects from the
  2354. behaviour of persistent connections implemented by Apache::DBI.
  2355.  
  2356. Caching connections can be useful in some applications, but it can
  2357. also cause problems, such as too many connections, and so should
  2358. be used with care.
  2359.  
  2360. The cache can be accessed (and cleared) via the L</CachedKids> attribute.
  2361.  
  2362.  
  2363. =item C<available_drivers>
  2364.  
  2365.   @ary = DBI->available_drivers;
  2366.   @ary = DBI->available_drivers($quiet);
  2367.  
  2368. Returns a list of all available drivers by searching for C<DBD::*> modules
  2369. through the directories in C<@INC>. By default, a warning is given if
  2370. some drivers are hidden by others of the same name in earlier
  2371. directories. Passing a true value for C<$quiet> will inhibit the warning.
  2372.  
  2373.  
  2374. =item C<installed_versions>
  2375.  
  2376.   DBI->installed_versions;
  2377.   @ary  = DBI->installed_versions;
  2378.   %hash = DBI->installed_versions;
  2379.  
  2380. Calls available_drivers() and attempts to load each of them in turn
  2381. using install_driver().  For each load that succeeds the driver
  2382. name and version number are added to a hash. When running under
  2383. L<DBI::PurePerl> drivers which appear not be pure-perl are ignored.
  2384.  
  2385. When called in array context the list of successfully loaded drivers
  2386. is returned (without the 'DBD::' prefix).
  2387.  
  2388. When called in scalar context a reference to the hash is returned
  2389. and the hash will also contain other entries for the C<DBI> version,
  2390. C<OS> name, etc.
  2391.  
  2392. When called in a void context the installed_versions() method will
  2393. print out a formatted list of the hash contents, one per line.
  2394.  
  2395. Due to the potentially high memory cost and unknown risks of loading
  2396. in an unknown number of drivers that just happen to be installed
  2397. on the system, this method is nor recommended for general use.
  2398. It is primarily intended as a quick way to see from the command
  2399. line what's installed. For example:
  2400.  
  2401.   perl -MDBI -e 'DBI->installed_versions'
  2402.  
  2403. The installed_versions() method was added in DBI 1.38.
  2404.  
  2405. =item C<data_sources>
  2406.  
  2407.   @ary = DBI->data_sources($driver);
  2408.   @ary = DBI->data_sources($driver, \%attr);
  2409.  
  2410. Returns a list of data sources (databases) available via the named
  2411. driver.  If C<$driver> is empty or C<undef>, then the value of the
  2412. C<DBI_DRIVER> environment variable is used.
  2413.  
  2414. The driver will be loaded if it hasn't been already. Note that if the
  2415. driver loading fails then data_sources() I<dies> with an error message
  2416. that includes the string "C<install_driver>" and the underlying problem.
  2417.  
  2418. Data sources are returned in a form suitable for passing to the
  2419. L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix).
  2420.  
  2421. Note that many drivers have no way of knowing what data sources might
  2422. be available for it. These drivers return an empty or incomplete list
  2423. or may require driver-specific attributes.
  2424.  
  2425. There is also a data_sources() method defined for database handles.
  2426.  
  2427.  
  2428. =item C<trace>
  2429.  
  2430.   DBI->trace($trace_level)
  2431.   DBI->trace($trace_level, $trace_filename)
  2432.  
  2433. DBI trace information can be enabled for all handles using the C<trace>
  2434. DBI class method. To enable trace information for a specific handle, use
  2435. the similar C<$h-E<gt>trace> method described elsewhere.
  2436.  
  2437. Trace levels are as follows:
  2438.  
  2439.   0 - Trace disabled.
  2440.   1 - Trace DBI method calls returning with results or errors.
  2441.   2 - Trace method entry with parameters and returning with results.
  2442.   3 - As above, adding some high-level information from the driver
  2443.       and some internal information from the DBI.
  2444.   4 - As above, adding more detailed information from the driver.
  2445.   5 and above - As above but with more and more obscure information.
  2446.  
  2447. Trace level 1 is best for a simple overview of what's happening.
  2448. Trace level 2 is a good choice for general purpose tracing.  Levels 3
  2449. and above (up to 9) are best reserved for investigating a
  2450. specific problem, when you need to see "inside" the driver and DBI.
  2451.  
  2452. The trace output is detailed and typically very useful. Much of the
  2453. trace output is formatted using the L</neat> function, so strings
  2454. in the trace output may be edited and truncated.
  2455.  
  2456. Initially trace output is written to C<STDERR>.  If C<$trace_filename> is
  2457. specified and can be opened in append mode then all trace
  2458. output (including that from other handles) is redirected to that file.
  2459. A warning is generated is the file can't be opened.
  2460. Further calls to C<trace> without a C<$trace_filename> do not alter where
  2461. the trace output is sent. If C<$trace_filename> is undefined, then
  2462. trace output is sent to C<STDERR> and the previous trace file is closed.
  2463. The C<trace> method returns the I<previous> tracelevel.
  2464.  
  2465. See also the C<$h-E<gt>trace> and C<$h-E<gt>trace_msg> methods and the
  2466. L</DEBUGGING> section
  2467. for information about the C<DBI_TRACE> environment variable.
  2468.  
  2469.  
  2470. =back
  2471.  
  2472.  
  2473. =head2 DBI Utility Functions
  2474.  
  2475. In addition to the methods listed in the previous section,
  2476. the DBI package also provides these utility functions:
  2477.  
  2478. =over 4
  2479.  
  2480. =item C<neat>
  2481.  
  2482.   $str = DBI::neat($value);
  2483.   $str = DBI::neat($value, $maxlen);
  2484.  
  2485. Return a string containing a neat (and tidy) representation of the
  2486. supplied value.
  2487.  
  2488. Strings will be quoted, although internal quotes will I<not> be escaped.
  2489. Values known to be numeric will be unquoted. Undefined (NULL) values
  2490. will be shown as C<undef> (without quotes).
  2491.  
  2492. If the string is flagged internally as utf8 then double quotes will
  2493. be used, otherwise single quotes are used and unprintable characters
  2494. will be replaced by dot (.).
  2495.  
  2496. For result strings longer than C<$maxlen> the result string will be
  2497. truncated to C<$maxlen-4> and "C<...'>" will be appended.  If C<$maxlen> is 0
  2498. or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400.
  2499.  
  2500. This function is designed to format values for human consumption.
  2501. It is used internally by the DBI for L</trace> output. It should
  2502. typically I<not> be used for formatting values for database use.
  2503. (See also L</quote>.)
  2504.  
  2505. =item C<neat_list>
  2506.  
  2507.   $str = DBI::neat_list(\@listref, $maxlen, $field_sep);
  2508.  
  2509. Calls C<DBI::neat> on each element of the list and returns a string
  2510. containing the results joined with C<$field_sep>. C<$field_sep> defaults
  2511. to C<", ">.
  2512.  
  2513. =item C<looks_like_number>
  2514.  
  2515.   @bool = DBI::looks_like_number(@array);
  2516.  
  2517. Returns true for each element that looks like a number.
  2518. Returns false for each element that does not look like a number.
  2519. Returns C<undef> for each element that is undefined or empty.
  2520.  
  2521. =item C<hash>
  2522.  
  2523.   $hash_value = DBI::hash($buffer, $type);
  2524.  
  2525. Return a 32-bit integer 'hash' value corresponding to the contents of $buffer.
  2526. The $type parameter selects which kind of hash algorithm should be used.
  2527.  
  2528. For the technically curious, type 0 (which is the default if $type
  2529. isn't specified) is based on the Perl 5.1 hash except that the value
  2530. is forced to be negative (for obscure historical reasons).
  2531. Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See
  2532. L<http://www.isthe.com/chongo/tech/comp/fnv/> for more information.
  2533. Both types are implemented in C and are very fast.
  2534.  
  2535. This function doesn't have much to do with databases, except that
  2536. it can be handy to store hash values in a database.
  2537.  
  2538. =back
  2539.  
  2540.  
  2541. =head2 DBI Dynamic Attributes
  2542.  
  2543. Dynamic attributes are always associated with the I<last handle used>
  2544. (that handle is represented by C<$h> in the descriptions below).
  2545.  
  2546. Where an attribute is equivalent to a method call, then refer to
  2547. the method call for all related documentation.
  2548.  
  2549. Warning: these attributes are provided as a convenience but they
  2550. do have limitations. Specifically, they have a short lifespan:
  2551. because they are associated with
  2552. the last handle used, they should only be used I<immediately> after
  2553. calling the method that "sets" them.
  2554. If in any doubt, use the corresponding method call.
  2555.  
  2556. =over 4
  2557.  
  2558. =item C<$DBI::err>
  2559.  
  2560. Equivalent to C<$h-E<gt>err>.
  2561.  
  2562. =item C<$DBI::errstr>
  2563.  
  2564. Equivalent to C<$h-E<gt>errstr>.
  2565.  
  2566. =item C<$DBI::state>
  2567.  
  2568. Equivalent to C<$h-E<gt>state>.
  2569.  
  2570. =item C<$DBI::rows>
  2571.  
  2572. Equivalent to C<$h-E<gt>rows>. Please refer to the documentation
  2573. for the L</rows> method.
  2574.  
  2575. =item C<$DBI::lasth>
  2576.  
  2577. Returns the DBI object handle used for the most recent DBI method call.
  2578. If the last DBI method call was a DESTROY then $DBI::lasth will return
  2579. the handle of the parent of the destroyed handle, if there is one.
  2580.  
  2581. =back
  2582.  
  2583.  
  2584. =head1 METHODS COMMON TO ALL HANDLES
  2585.  
  2586. The following methods can be used by all types of DBI handles.
  2587.  
  2588. =over 4
  2589.  
  2590. =item C<err>
  2591.  
  2592.   $rv = $h->err;
  2593.  
  2594. Returns the I<native> database engine error code from the last driver
  2595. method called. The code is typically an integer but you should not
  2596. assume that.
  2597.  
  2598. The DBI resets $h->err to undef before most DBI method calls, so the
  2599. value only has a short lifespan. Also, most drivers share the same
  2600. error variables across all their handles, so calling a method on
  2601. one handle will typically reset the error on all the other handles
  2602. that are children of that driver.
  2603.  
  2604. If you need to test for individual errors I<and> have your program be
  2605. portable to different database engines, then you'll need to determine
  2606. what the corresponding error codes are for all those engines and test for
  2607. all of them.
  2608.  
  2609. =item C<errstr>
  2610.  
  2611.   $str = $h->errstr;
  2612.  
  2613. Returns the native database engine error message from the last driver
  2614. method called. This has the same lifespan issues as the L</err> method
  2615. described above.
  2616.  
  2617. =item C<state>
  2618.  
  2619.   $str = $h->state;
  2620.  
  2621. Returns an error code in the standard SQLSTATE five character format.
  2622. Note that the specific success code C<00000> is translated to 'C<>'
  2623. (false). If the driver does not support SQLSTATE (and most don't),
  2624. then state will return C<S1000> (General Error) for all errors.
  2625.  
  2626. The driver is free to return any value via C<state>, e.g., warning
  2627. codes, even if it has not declared an error by returning a true value
  2628. via the L</err> method described above.
  2629.  
  2630. =item C<set_err>
  2631.  
  2632.   $rv = $h->set_err($err, $errstr);
  2633.   $rv = $h->set_err($err, $errstr, $state, $method);
  2634.   $rv = $h->set_err($err, $errstr, $state, $method, $rv);
  2635.  
  2636. Set the C<err>, C<errstr>, and C<state> values for the handle.
  2637. This will trigger the normal DBI error handling mechanisms,
  2638. such as C<RaiseError> and C<HandleError>, if they are enabled.
  2639. This method is typically only used by DBI drivers and DBI subclasses.
  2640.  
  2641. The $method parameter provides an alternate method name, instead
  2642. of the fairly unhelpful 'C<set_err>', for the
  2643. C<RaiseError>/C<PrintError> error string.
  2644.  
  2645. The C<set_err> method normally returns undef.  The $rv parameter
  2646. provides an alternate return value. The C<HandleError> subroutine
  2647. can access and alter this value.
  2648.  
  2649. =item C<trace>
  2650.  
  2651.   $h->trace($trace_level);
  2652.   $h->trace($trace_level, $trace_filename);
  2653.  
  2654. DBI trace information can be enabled for a specific handle (and any
  2655. future children of that handle) by setting the trace level using the
  2656. C<trace> method.
  2657.  
  2658. Trace level 1 is best for a simple overview of what's happening.
  2659. Trace level 2 is a good choice for general purpose tracing.  Levels 3
  2660. and above (up to 9) are best reserved for investigating a
  2661. specific problem, when you need to see "inside" the driver and DBI.
  2662. Set C<$trace_level> to 0 to disable the trace.
  2663.  
  2664. The trace output is detailed and typically very useful. Much of the
  2665. trace output is formatted using the L</neat> function, so strings
  2666. in the trace output may be edited and truncated.
  2667.  
  2668. Initially, trace output is written to C<STDERR>.  If C<$trace_filename> is
  2669. specified, then the file is opened in append mode and I<all> trace
  2670. output (including that from other handles) is redirected to that file.
  2671. Further calls to trace without a C<$trace_filename> do not alter where
  2672. the trace output is sent. If C<$trace_filename> is undefined, then
  2673. trace output is sent to C<STDERR> and the previous trace file is closed.
  2674.  
  2675. See also the C<DBI-E<gt>trace> method, the C<$h-E<gt>{TraceLevel}> attribute,
  2676. and L</DEBUGGING> for information about the C<DBI_TRACE> environment variable.
  2677.  
  2678.  
  2679. =item C<trace_msg>
  2680.  
  2681.   $h->trace_msg($message_text);
  2682.   $h->trace_msg($message_text, $min_level);
  2683.  
  2684. Writes C<$message_text> to the trace file if trace is enabled for C<$h> or
  2685. for the DBI as a whole. Can also be called as C<DBI-E<gt>trace_msg($msg)>.
  2686. See L</trace>.
  2687.  
  2688. If C<$min_level> is defined, then the message is output only if the trace
  2689. level is equal to or greater than that level. C<$min_level> defaults to 1.
  2690.  
  2691.  
  2692. =item C<func>
  2693.  
  2694.   $h->func(@func_arguments, $func_name) or die ...;
  2695.  
  2696. The C<func> method can be used to call private non-standard and
  2697. non-portable methods implemented by the driver. Note that the function
  2698. name is given as the I<last> argument.
  2699.  
  2700. It's also important to note that the func() method does not clear
  2701. a previous error ($DBI::err etc.) and it does not trigger automatic
  2702. error detection (RaiseError etc.) so you must check the return
  2703. status and/or $h->err to detect errors.
  2704.  
  2705. (This method is not directly related to calling stored procedures.
  2706. Calling stored procedures is currently not defined by the DBI.
  2707. Some drivers, such as DBD::Oracle, support it in non-portable ways.
  2708. See driver documentation for more details.)
  2709.  
  2710. See also L</install_method> for how you can avoid needing to
  2711. use func() and gain.
  2712.  
  2713. =item C<can>
  2714.  
  2715.   $is_implemented = $h->can($method_name);
  2716.  
  2717. Returns true if $method_name is implemented by the driver or a
  2718. default method is provided by the DBI.
  2719. It returns false where a driver hasn't implemented a method and the
  2720. default method is provided by the DBI is just an empty stub.
  2721.  
  2722. =back
  2723.  
  2724.  
  2725. =head1 ATTRIBUTES COMMON TO ALL HANDLES
  2726.  
  2727. These attributes are common to all types of DBI handles.
  2728.  
  2729. Some attributes are inherited by child handles. That is, the value
  2730. of an inherited attribute in a newly created statement handle is the
  2731. same as the value in the parent database handle. Changes to attributes
  2732. in the new statement handle do not affect the parent database handle
  2733. and changes to the database handle do not affect existing statement
  2734. handles, only future ones.
  2735.  
  2736. Attempting to set or get the value of an unknown attribute is fatal,
  2737. except for private driver specific attributes (which all have names
  2738. starting with a lowercase letter).
  2739.  
  2740. Example:
  2741.  
  2742.   $h->{AttributeName} = ...;    # set/write
  2743.   ... = $h->{AttributeName};    # get/read
  2744.  
  2745. =over 4
  2746.  
  2747. =item C<Warn> (boolean, inherited)
  2748.  
  2749. The C<Warn> attribute enables useful warnings for certain bad practices. Enabled by default. Some
  2750. emulation layers, especially those for Perl 4 interfaces, disable warnings.
  2751. Since warnings are generated using the Perl C<warn> function, they can be
  2752. intercepted using the Perl C<$SIG{__WARN__}> hook.
  2753.  
  2754. =item C<Active> (boolean, read-only)
  2755.  
  2756. The C<Active> attribute is true if the handle object is "active". This is rarely used in
  2757. applications. The exact meaning of active is somewhat vague at the
  2758. moment. For a database handle it typically means that the handle is
  2759. connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off).  For
  2760. a statement handle it typically means that the handle is a C<SELECT>
  2761. that may have more data to fetch. (Fetching all the data or calling C<$sth-E<gt>finish>
  2762. sets C<Active> off.)
  2763.  
  2764. =item C<Kids> (integer, read-only)
  2765.  
  2766. For a driver handle, C<Kids> is the number of currently existing database
  2767. handles that were created from that driver handle.  For a database
  2768. handle, C<Kids> is the number of currently existing statement handles that
  2769. were created from that database handle.
  2770. For a statement handle, the value is zero.
  2771.  
  2772. =item C<ActiveKids> (integer, read-only)
  2773.  
  2774. Like C<Kids>, but only counting those that are C<Active> (as above).
  2775.  
  2776. =item C<CachedKids> (hash ref)
  2777.  
  2778. For a database handle, C<CachedKids> returns a reference to the cache (hash) of
  2779. statement handles created by the L</prepare_cached> method.  For a
  2780. driver handle, returns a reference to the cache (hash) of
  2781. database handles created by the L</connect_cached> method.
  2782.  
  2783. =item C<CompatMode> (boolean, inherited)
  2784.  
  2785. The C<CompatMode> attribute is used by emulation layers (such as
  2786. Oraperl) to enable compatible behaviour in the underlying driver
  2787. (e.g., DBD::Oracle) for this handle. Not normally set by application code.
  2788.  
  2789. It also has the effect of disabling the 'quick FETCH' of attribute
  2790. values from the handles attribute cache. So all attribute values
  2791. are handled by the drivers own FETCH method. This makes them slightly
  2792. slower but is useful for special-purpose drivers like DBD::Multiplex.
  2793.  
  2794. =item C<InactiveDestroy> (boolean)
  2795.  
  2796. The C<InactiveDestroy> attribute can be used to disable the I<database
  2797. engine> related effect of DESTROYing a handle (which would normally
  2798. close a prepared statement or disconnect from the database etc).
  2799. The default value, false, means a handle will be fully destroyed
  2800. when it passes out of scope.
  2801.  
  2802. For a database handle, this attribute does not disable an I<explicit>
  2803. call to the disconnect method, only the implicit call from DESTROY
  2804. that happens if the handle is still marked as C<Active>.
  2805.  
  2806. Think of the name as meaning 'treat the handle as not-Active in the
  2807. DESTROY method'.
  2808.  
  2809. This attribute is specifically designed for use in Unix applications
  2810. that "fork" child processes. Either the parent or the child process,
  2811. but not both, should set C<InactiveDestroy> on all their shared handles.
  2812. Note that some databases, including Oracle, don't support passing a
  2813. database connection across a fork.
  2814.  
  2815. To help tracing applications using fork the process id is shown in
  2816. the trace log whenever a DBI or handle trace() method is called.
  2817. The process id also shown for I<every> method call if the DBI trace
  2818. level (not handle trace level) is set high enough to show the trace
  2819. from the DBI's method dispatcher, e.g. >= 9.
  2820.  
  2821. =item C<PrintError> (boolean, inherited)
  2822.  
  2823. The C<PrintError> attribute can be used to force errors to generate warnings (using
  2824. C<warn>) in addition to returning error codes in the normal way.  When set
  2825. "on", any method which results in an error occuring will cause the DBI to
  2826. effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class>
  2827. is the driver class and C<$method> is the name of the method which failed. E.g.,
  2828.  
  2829.   DBD::Oracle::db prepare failed: ... error text here ...
  2830.  
  2831. By default, C<DBI-E<gt>connect> sets C<PrintError> "on".
  2832.  
  2833. If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}>
  2834. handler or modules like CGI::Carp and CGI::ErrorWrap.
  2835.  
  2836. =item C<RaiseError> (boolean, inherited)
  2837.  
  2838. The C<RaiseError> attribute can be used to force errors to raise exceptions rather
  2839. than simply return error codes in the normal way. It is "off" by default.
  2840. When set "on", any method which results in an error will cause
  2841. the DBI to effectively do a C<die("$class $method failed: $DBI::errstr")>,
  2842. where C<$class> is the driver class and C<$method> is the name of the method
  2843. that failed. E.g.,
  2844.  
  2845.   DBD::Oracle::db prepare failed: ... error text here ...
  2846.  
  2847. If you turn C<RaiseError> on then you'd normally turn C<PrintError> off.
  2848. If C<PrintError> is also on, then the C<PrintError> is done first (naturally).
  2849.  
  2850. Typically C<RaiseError> is used in conjunction with C<eval { ... }>
  2851. to catch the exception that's been thrown and followed by an
  2852. C<if ($@) { ... }> block to handle the caught exception. In that eval
  2853. block the $DBI::lasth variable can be useful for diagnosis and reporting.
  2854. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}.
  2855.  
  2856. If you want to temporarily turn C<RaiseError> off (inside a library function
  2857. that is likely to fail, for example), the recommended way is like this:
  2858.  
  2859.   {
  2860.     local $h->{RaiseError};  # localize and turn off for this block
  2861.     ...
  2862.   }
  2863.  
  2864. The original value will automatically and reliably be restored by Perl,
  2865. regardless of how the block is exited.
  2866. The same logic applies to other attributes, including C<PrintError>.
  2867.  
  2868. =item C<HandleError> (code ref, inherited)
  2869.  
  2870. The C<HandleError> attribute can be used to provide your own alternative behaviour
  2871. in case of errors. If set to a reference to a subroutine then that
  2872. subroutine is called when an error is detected (at the same point that
  2873. C<RaiseError> and C<PrintError> are handled).
  2874.  
  2875. The subroutine is called with three parameters: the error message
  2876. string that C<RaiseError> and C<PrintError> would use,
  2877. the DBI handle being used, and the first value being returned by
  2878. the method that failed (typically undef).
  2879.  
  2880. If the subroutine returns a false value then the C<RaiseError>
  2881. and/or C<PrintError> attributes are checked and acted upon as normal.
  2882.  
  2883. For example, to C<die> with a full stack trace for any error:
  2884.  
  2885.   use Carp;
  2886.   $h->{HandleError} = sub { confess(shift) };
  2887.  
  2888. Or to turn errors into exceptions:
  2889.  
  2890.   use Exception; # or your own favourite exception module
  2891.   $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
  2892.  
  2893. It is possible to 'stack' multiple HandleError handlers by using
  2894. closures:
  2895.  
  2896.   sub your_subroutine {
  2897.     my $previous_handler = $h->{HandleError};
  2898.     $h->{HandleError} = sub {
  2899.       return 1 if $previous_handler and &$previous_handler(@_);
  2900.       ... your code here ...
  2901.     };
  2902.   }
  2903.  
  2904. Using a C<my> inside a subroutine to store the previous C<HandleError>
  2905. value is important.  See L<perlsub> and L<perlref> for more information
  2906. about I<closures>.
  2907.  
  2908. It is possible for C<HandleError> to alter the error message that
  2909. will be used by C<RaiseError> and C<PrintError> if it returns false.
  2910. It can do that by altering the value of $_[0]. This example appends
  2911. a stack trace to all errors and, unlike the previous example using
  2912. Carp::confess, this will work C<PrintError> as well as C<RaiseError>:
  2913.  
  2914.   $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; };
  2915.  
  2916. It is also possible for C<HandleError> to hide an error, to a limited
  2917. degree, by using L</set_err> to reset $DBI::err and $DBI::errstr,
  2918. and altering the return value of the failed method. For example:
  2919.  
  2920.   $h->{HandleError} = sub {
  2921.     return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/;
  2922.     return 0 unless $_[1]->err == 1234; # the error to 'hide'
  2923.     $h->set_err(0,"");    # turn off the error
  2924.     $_[2] = [ ... ];    # supply alternative return value
  2925.     return 1;
  2926.   };
  2927.  
  2928. This only works for methods which return a single value and is hard
  2929. to make reliable (avoiding infinite loops, for example) and so isn't
  2930. recommended for general use!  If you find a I<good> use for it then
  2931. please let me know.
  2932.  
  2933.  
  2934. =item C<ShowErrorStatement> (boolean, inherited)
  2935.  
  2936. The C<ShowErrorStatement> attribute can be used to cause the relevant Statement text to be
  2937. appended to the error messages generated by the C<RaiseError> and
  2938. C<PrintError> attributes. Only applies to errors on statement handles
  2939. plus the prepare(), do(), and the various C<select*()> database handle methods.
  2940. (The exact format of the appended text is subject to change.)
  2941.  
  2942. If C<$h-E<gt>{ParamValues}> returns a hash reference of parameter
  2943. (placeholder) values then those are formatted and appended to the
  2944. end of the Statement text in the error message.
  2945.  
  2946. =item C<TraceLevel> (integer, inherited)
  2947.  
  2948. The C<TraceLevel> attribute can be used as an alternative to the L</trace> method
  2949. to set the DBI trace level for a specific handle.
  2950.  
  2951. =item C<FetchHashKeyName> (string, inherited)
  2952.  
  2953. The C<FetchHashKeyName> attribute is used to specify whether the fetchrow_hashref()
  2954. method should perform case conversion on the field names used for
  2955. the hash keys. For historical reasons it defaults to 'C<NAME>' but
  2956. it is recommended to set it to 'C<NAME_lc>' (convert to lower case)
  2957. or 'C<NAME_uc>' (convert to upper case) according to your preference.
  2958. It can only be set for driver and database handles.  For statement
  2959. handles the value is frozen when prepare() is called.
  2960.  
  2961.  
  2962. =item C<ChopBlanks> (boolean, inherited)
  2963.  
  2964. The C<ChopBlanks> attribute can be used to control the trimming of trailing space
  2965. characters from fixed width character (CHAR) fields. No other field
  2966. types are affected, even where field values have trailing spaces.
  2967.  
  2968. The default is false (although it is possible that the default may change).
  2969. Applications that need specific behaviour should set the attribute as
  2970. needed. Emulation interfaces should set the attribute to match the
  2971. behaviour of the interface they are emulating.
  2972.  
  2973. Drivers are not required to support this attribute, but any driver which
  2974. does not support it must arrange to return C<undef> as the attribute value.
  2975.  
  2976.  
  2977. =item C<LongReadLen> (unsigned integer, inherited)
  2978.  
  2979. The C<LongReadLen> attribute may be used to control the maximum length of long fields
  2980. ("blob", "memo", etc.) which the driver will read from the
  2981. database automatically when it fetches each row of data.  The
  2982. C<LongReadLen> attribute only relates to fetching and reading long values; it
  2983. is not involved in inserting or updating them.
  2984.  
  2985. A value of 0 means not to automatically fetch any long data. (C<fetch>
  2986. should return C<undef> for long fields when C<LongReadLen> is 0.)
  2987.  
  2988. The default is typically 0 (zero) bytes but may vary between drivers.
  2989. Applications fetching long fields should set this value to slightly
  2990. larger than the longest long field value to be fetched.
  2991.  
  2992. Some databases return some long types encoded as pairs of hex digits.
  2993. For these types, C<LongReadLen> relates to the underlying data length and not the
  2994. doubled-up length of the encoded string.
  2995.  
  2996. Changing the value of C<LongReadLen> for a statement handle after it
  2997. has been C<prepare>'d will typically have no effect, so it's common to
  2998. set C<LongReadLen> on the C<$dbh> before calling C<prepare>.
  2999.  
  3000. Note that the value used here has a direct effect on the memory used
  3001. by the application, so don't be too generous.
  3002.  
  3003. See L</LongTruncOk> for more information on truncation behaviour.
  3004.  
  3005. =item C<LongTruncOk> (boolean, inherited)
  3006.  
  3007. The C<LongTruncOk> attribute may be used to control the effect of fetching a long
  3008. field value which has been truncated (typically because it's longer
  3009. than the value of the C<LongReadLen> attribute).
  3010.  
  3011. By default, C<LongTruncOk> is false and so fetching a long value that
  3012. needs to be truncated will cause the fetch to fail.
  3013. (Applications should always be sure to
  3014. check for errors after a fetch loop in case an error, such as a divide
  3015. by zero or long field truncation, caused the fetch to terminate
  3016. prematurely.)
  3017.  
  3018. If a fetch fails due to a long field truncation when C<LongTruncOk> is
  3019. false, many drivers will allow you to continue fetching further rows.
  3020.  
  3021. See also L</LongReadLen>.
  3022.  
  3023. =item C<TaintIn> (boolean, inherited)
  3024.  
  3025. If the C<TaintIn> attribute is set to a true value I<and> Perl is running in
  3026. taint mode (e.g., started with the C<-T> option), then all the arguments
  3027. to most DBI method calls are checked for being tainted. I<This may change.>
  3028.  
  3029. The attribute defaults to off, even if Perl is in taint mode.
  3030. See L<perlsec> for more about taint mode.  If Perl is not
  3031. running in taint mode, this attribute has no effect.
  3032.  
  3033. When fetching data that you trust you can turn off the TaintIn attribute,
  3034. for that statement handle, for the duration of the fetch loop.
  3035.  
  3036. The C<TaintIn> attribute was added in DBI 1.31.
  3037.  
  3038. =item C<TaintOut> (boolean, inherited)
  3039.  
  3040. If the C<TaintOut> attribute is set to a true value I<and> Perl is running in
  3041. taint mode (e.g., started with the C<-T> option), then most data fetched
  3042. from the database is considered tainted. I<This may change.>
  3043.  
  3044. The attribute defaults to off, even if Perl is in taint mode.
  3045. See L<perlsec> for more about taint mode.  If Perl is not
  3046. running in taint mode, this attribute has no effect.
  3047.  
  3048. When fetching data that you trust you can turn off the TaintOut attribute,
  3049. for that statement handle, for the duration of the fetch loop.
  3050.  
  3051. Currently only fetched data is tainted. It is possible that the results
  3052. of other DBI method calls, and the value of fetched attributes, may
  3053. also be tainted in future versions. That change may well break your
  3054. applications unless you take great care now. If you use DBI Taint mode,
  3055. please report your experience and any suggestions for changes.
  3056.  
  3057. The C<TaintOut> attribute was added in DBI 1.31.
  3058.  
  3059. =item C<Taint> (boolean, inherited)
  3060.  
  3061. The C<Taint> attribute is a shortcut for L</TaintIn> and L</TaintOut> (it is also present
  3062. for backwards compatibility).
  3063.  
  3064. Setting this attribute sets both L</TaintIn> and L</TaintOut>, and retrieving
  3065. it returns a true value if and only if L</TaintIn> and L</TaintOut> are
  3066. both set to true values.
  3067.  
  3068. =item C<Profile> (inherited)
  3069.  
  3070. The C<Profile> attribute enables the collection and reporting of method call timing statistics.
  3071. See the L<DBI::Profile> module documentation for I<much> more detail.
  3072.  
  3073. The C<Profile> attribute was added in DBI 1.24.
  3074.  
  3075. =item C<private_your_module_name_*>
  3076.  
  3077. The DBI provides a way to store extra information in a DBI handle as
  3078. "private" attributes. The DBI will allow you to store and retrieve any
  3079. attribute which has a name starting with "C<private_>".
  3080.  
  3081. It is I<strongly> recommended that you use just I<one> private
  3082. attribute (e.g., use a hash ref) I<and> give it a long and unambiguous
  3083. name that includes the module or application name that the attribute
  3084. relates to (e.g., "C<private_YourFullModuleName_thingy>").
  3085.  
  3086. Because of the way the Perl tie mechanism works you cannot reliably
  3087. use the C<||=> operator directly to initialise the attribute, like this:
  3088.  
  3089.   my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG
  3090.  
  3091. you should use a two step approach like this:
  3092.  
  3093.   my $foo = $dbh->{private_yourmodname_foo};
  3094.   $foo ||= $dbh->{private_yourmodname_foo} = { ... };
  3095.  
  3096. This attribute is primarily of interest to people sub-classing DBI.
  3097.  
  3098. =back
  3099.  
  3100.  
  3101. =head1 DBI DATABASE HANDLE OBJECTS
  3102.  
  3103. This section covers the methods and attributes associated with
  3104. database handles.
  3105.  
  3106. =head2 Database Handle Methods
  3107.  
  3108. The following methods are specified for DBI database handles:
  3109.  
  3110. =over 4
  3111.  
  3112. =item C<clone>
  3113.  
  3114.   $new_dbh = $dbh->clone();
  3115.   $new_dbh = $dbh->clone(\%attr);
  3116.  
  3117. The C<clone> method duplicates the $dbh connection by connecting
  3118. with the same parameters ($dsn, $user, $password) as originally used.
  3119.  
  3120. The attributes for the cloned connect are the same as those used
  3121. for the original connect, with some other attribute merged over
  3122. them depending on the \%attr parameter.
  3123.  
  3124. If \%attr is given then the attributes it contains are merged into
  3125. the original attributes and override any with the same names.
  3126. Effectively the same as doing:
  3127.  
  3128.   %attribues_used = ( %original_attributes, %attr );
  3129.  
  3130. If \%attr is not given then it defaults to a hash containing all
  3131. the attributes in the attribute cache of $dbh excluding any non-code
  3132. references, plus the main boolean attributes (RaiseError, PrintError,
  3133. AutoCommit, etc.). This behaviour is subject to change.
  3134.  
  3135. The clone method can be used even if the database handle is disconnected.
  3136.  
  3137. The C<clone> method was added in DBI 1.33. It is very new and likely
  3138. to change.
  3139.  
  3140. =item C<data_sources>
  3141.  
  3142.   @ary = $dbh->data_sources();
  3143.   @ary = $dbh->data_sources(\%attr);
  3144.  
  3145. Returns a list of data sources (databases) available via the $dbh
  3146. driver's data_sources() method, plus any extra data sources that
  3147. the driver can discover via the connected $dbh. Typically the extra
  3148. data sources are other databases managed by the same server process
  3149. that the $dbh is connected to.
  3150.  
  3151. Data sources are returned in a form suitable for passing to the
  3152. L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix).
  3153.  
  3154. The data_sources() method, for a $dbh, was added in DBI 1.38.
  3155.  
  3156. =item C<do>
  3157.  
  3158.   $rows = $dbh->do($statement)           or die $dbh->errstr;
  3159.   $rows = $dbh->do($statement, \%attr)   or die $dbh->errstr;
  3160.   $rows = $dbh->do($statement, \%attr, @bind_values) or die ...
  3161.  
  3162. Prepare and execute a single statement. Returns the number of rows
  3163. affected or C<undef> on error. A return value of C<-1> means the
  3164. number of rows is not known, not applicable, or not available.
  3165.  
  3166. This method is typically most useful for I<non>-C<SELECT> statements that
  3167. either cannot be prepared in advance (due to a limitation of the
  3168. driver) or do not need to be executed repeatedly. It should not
  3169. be used for C<SELECT> statements because it does not return a statement
  3170. handle (so you can't fetch any data).
  3171.  
  3172. The default C<do> method is logically similar to:
  3173.  
  3174.   sub do {
  3175.       my($dbh, $statement, $attr, @bind_values) = @_;
  3176.       my $sth = $dbh->prepare($statement, $attr) or return undef;
  3177.       $sth->execute(@bind_values) or return undef;
  3178.       my $rows = $sth->rows;
  3179.       ($rows == 0) ? "0E0" : $rows; # always return true if no error
  3180.   }
  3181.  
  3182. For example:
  3183.  
  3184.   my $rows_deleted = $dbh->do(q{
  3185.       DELETE FROM table
  3186.       WHERE status = ?
  3187.   }, undef, 'DONE') or die $dbh->errstr;
  3188.  
  3189. Using placeholders and C<@bind_values> with the C<do> method can be
  3190. useful because it avoids the need to correctly quote any variables
  3191. in the C<$statement>. But if you'll be executing the statement many
  3192. times then it's more efficient to C<prepare> it once and call
  3193. C<execute> many times instead.
  3194.  
  3195. The C<q{...}> style quoting used in this example avoids clashing with
  3196. quotes that may be used in the SQL statement. Use the double-quote-like
  3197. C<qq{...}> operator if you want to interpolate variables into the string.
  3198. See L<perlop/"Quote and Quote-like Operators"> for more details.
  3199.  
  3200. =item C<last_insert_id>
  3201.  
  3202.   $rv = $dbh->last_insert_id($catalog, $schema, $table, $field);
  3203.   $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr);
  3204.  
  3205. Returns a value 'identifying' the row just inserted, if possible.
  3206. Typically this would be a value assigned by the database server
  3207. to a column with an I<auto_increment> or I<serial> type.
  3208. Returns undef if the driver does not support the method or can't
  3209. determine the value.
  3210.  
  3211. The $catalog, $schema, $table, and $field parameters may be required
  3212. for some drivers (see below).  If you don't know the parameter values
  3213. and your driver does not need them, then use C<undef> for each.
  3214.  
  3215. There are several caveats to be aware of with this method if you want
  3216. to use it for portable applications:
  3217.  
  3218. B<*> For some drivers the value may only available immediately after
  3219. the insert statement has executed (e.g., mysql, Informix).
  3220.  
  3221. B<*> For some drivers the $catalog, $schema, $table, and $field parameters
  3222. are required (e.g., Pg), for others they are ignored (e.g., mysql).
  3223.  
  3224. B<*> Drivers may return an indeterminate value if no insert has
  3225. been performed yet.
  3226.  
  3227. B<*> For some drivers the value may only be available if placeholders
  3228. have I<not> been used (e.g., Sybase, MS SQL). In this case the value
  3229. returned would be from the last non-placeholder insert statement.
  3230.  
  3231. B<*> Some drivers may need driver-specific hints about how to get
  3232. the value. For example, being told the name of the database 'sequence'
  3233. object that holds the value. Any such hints are passed as driver-specific
  3234. attributes in the \%attr parameter.
  3235.  
  3236. B<*> If the underlying database offers nothing better, then some
  3237. drivers may attempt to implement this method by executing
  3238. "C<select max($field) from $table>". Drivers using any approach
  3239. like this should issue a warning if C<AutoCommit> is true because
  3240. it is generally unsafe - another process may have modified the table
  3241. between your insert and the select. For situations where you know
  3242. it is safe, such as when you have locked the table, you can silence
  3243. the warning by passing C<Warn> => 0 in \%attr.
  3244.  
  3245. B<*> If no insert has been performed yet, or the last insert failed,
  3246. then the value is implementation defined.
  3247.  
  3248. Given all the caveats above, it's clear that this method must be
  3249. used with care.
  3250.  
  3251. The C<last_insert_id> method was added in DBI 1.38.
  3252.  
  3253. =item C<selectrow_array>
  3254.  
  3255.   @row_ary = $dbh->selectrow_array($statement);
  3256.   @row_ary = $dbh->selectrow_array($statement, \%attr);
  3257.   @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
  3258.  
  3259. This utility method combines L</prepare>, L</execute> and
  3260. L</fetchrow_array> into a single call. If called in a list context, it
  3261. returns the first row of data from the statement.  The C<$statement>
  3262. parameter can be a previously prepared statement handle, in which case
  3263. the C<prepare> is skipped.
  3264.  
  3265. If any method fails, and L</RaiseError> is not set, C<selectrow_array>
  3266. will return an empty list.
  3267.  
  3268. If called in a scalar context for a statement handle that has more
  3269. than one column, it is undefined whether the driver will return
  3270. the value of the first column or the last. So don't do that.
  3271. Also, in a scalar context, an C<undef> is returned if there are no
  3272. more rows or if an error occurred. That C<undef> can't be distinguished
  3273. from an C<undef> returned because the first field value was NULL.
  3274. For these reasons you should exercise some caution if you use
  3275. C<selectrow_array> in a scalar context.
  3276.  
  3277.  
  3278. =item C<selectrow_arrayref>
  3279.  
  3280.   $ary_ref = $dbh->selectrow_arrayref($statement);
  3281.   $ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
  3282.   $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
  3283.  
  3284. This utility method combines L</prepare>, L</execute> and
  3285. L</fetchrow_arrayref> into a single call. It returns the first row of
  3286. data from the statement.  The C<$statement> parameter can be a previously
  3287. prepared statement handle, in which case the C<prepare> is skipped.
  3288.  
  3289. If any method fails, and L</RaiseError> is not set, C<selectrow_array>
  3290. will return undef.
  3291.  
  3292.  
  3293. =item C<selectrow_hashref>
  3294.  
  3295.   $hash_ref = $dbh->selectrow_hashref($statement);
  3296.   $hash_ref = $dbh->selectrow_hashref($statement, \%attr);
  3297.   $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values);
  3298.  
  3299. This utility method combines L</prepare>, L</execute> and
  3300. L</fetchrow_hashref> into a single call. It returns the first row of
  3301. data from the statement.  The C<$statement> parameter can be a previously
  3302. prepared statement handle, in which case the C<prepare> is skipped.
  3303.  
  3304. If any method fails, and L</RaiseError> is not set, C<selectrow_hashref>
  3305. will return undef.
  3306.  
  3307.  
  3308. =item C<selectall_arrayref>
  3309.  
  3310.   $ary_ref = $dbh->selectall_arrayref($statement);
  3311.   $ary_ref = $dbh->selectall_arrayref($statement, \%attr);
  3312.   $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
  3313.  
  3314. This utility method combines L</prepare>, L</execute> and
  3315. L</fetchall_arrayref> into a single call. It returns a reference to an
  3316. array containing a reference to an array for each row of data fetched.
  3317.  
  3318. The C<$statement> parameter can be a previously prepared statement handle,
  3319. in which case the C<prepare> is skipped. This is recommended if the
  3320. statement is going to be executed many times.
  3321.  
  3322. If L</RaiseError> is not set and any method except C<fetchall_arrayref>
  3323. fails then C<selectall_arrayref> will return C<undef>; if
  3324. C<fetchall_arrayref> fails then it will return with whatever data
  3325. has been fetched thus far. You should check C<$sth-E<gt>err>
  3326. afterwards (or use the C<RaiseError> attribute) to discover if the data is
  3327. complete or was truncated due to an error.
  3328.  
  3329. The L</fetchall_arrayref> method called by C<selectall_arrayref>
  3330. supports a $max_rows parameter. You can specify a value for $max_rows
  3331. by including a 'C<MaxRows>' attribute in \%attr.
  3332.  
  3333. The L</fetchall_arrayref> method called by C<selectall_arrayref>
  3334. also supports a $slice parameter. You can specify a value for $slice by
  3335. including a 'C<Slice>' or 'C<Columns>' attribute in \%attr. The only
  3336. difference between the two is that if C<Slice> is not defined and
  3337. C<Columns> is an array ref, then the array is assumed to contain column
  3338. index values (which count from 1), rather than perl array index values.
  3339. In which case the array is copied and each value decremented before
  3340. passing to C</fetchall_arrayref>.
  3341.  
  3342.  
  3343. =item C<selectall_hashref>
  3344.  
  3345.   $hash_ref = $dbh->selectall_hashref($statement, $key_field);
  3346.   $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr);
  3347.   $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values);
  3348.  
  3349. This utility method combines L</prepare>, L</execute> and
  3350. L</fetchall_hashref> into a single call. It returns a reference to a
  3351. hash containing one entry for each row. The key for each row entry is
  3352. specified by $key_field. The value is a reference to a hash returned by
  3353. C<fetchrow_hashref>.
  3354.  
  3355. The C<$statement> parameter can be a previously prepared statement handle,
  3356. in which case the C<prepare> is skipped. This is recommended if the
  3357. statement is going to be executed many times.
  3358.  
  3359. If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set,
  3360. C<selectall_hashref> will return C<undef>.  If C<fetchrow_hashref> fails and
  3361. L</RaiseError> is not set, then it will return with whatever data it
  3362. has fetched thus far. $DBI::err should be checked to catch that.
  3363.  
  3364.  
  3365. =item C<selectcol_arrayref>
  3366.  
  3367.   $ary_ref = $dbh->selectcol_arrayref($statement);
  3368.   $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
  3369.   $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
  3370.  
  3371. This utility method combines L</prepare>, L</execute>, and fetching one
  3372. column from all the rows, into a single call. It returns a reference to
  3373. an array containing the values of the first column from each row.
  3374.  
  3375. The C<$statement> parameter can be a previously prepared statement handle,
  3376. in which case the C<prepare> is skipped. This is recommended if the
  3377. statement is going to be executed many times.
  3378.  
  3379. If any method except C<fetch> fails, and L</RaiseError> is not set,
  3380. C<selectcol_arrayref> will return C<undef>.  If C<fetch> fails and
  3381. L</RaiseError> is not set, then it will return with whatever data it
  3382. has fetched thus far. $DBI::err should be checked to catch that.
  3383.  
  3384. The C<selectcol_arrayref> method defaults to pushing a single column
  3385. value (the first) from each row into the result array. However, it can
  3386. also push another column, or even multiple columns per row, into the
  3387. result array. This behaviour can be specified via a 'C<Columns>'
  3388. attribute which must be a ref to an array containing the column number
  3389. or numbers to use. For example:
  3390.  
  3391.   # get array of id and name pairs:
  3392.   my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] });
  3393.   my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name
  3394.  
  3395. You can specify a maximum number of rows to fetch by including a
  3396. 'C<MaxRows>' attribute in \%attr.
  3397.  
  3398. =item C<prepare>
  3399.  
  3400.   $sth = $dbh->prepare($statement)          or die $dbh->errstr;
  3401.   $sth = $dbh->prepare($statement, \%attr)  or die $dbh->errstr;
  3402.  
  3403. Prepares a statement for later execution by the database
  3404. engine and returns a reference to a statement handle object.
  3405.  
  3406. The returned statement handle can be used to get attributes of the
  3407. statement and invoke the L</execute> method. See L</Statement Handle Methods>.
  3408.  
  3409. Drivers for engines without the concept of preparing a
  3410. statement will typically just store the statement in the returned
  3411. handle and process it when C<$sth-E<gt>execute> is called. Such drivers are
  3412. unlikely to give much useful information about the
  3413. statement, such as C<$sth-E<gt>{NUM_OF_FIELDS}>, until after C<$sth-E<gt>execute>
  3414. has been called. Portable applications should take this into account.
  3415.  
  3416. In general, DBI drivers do not parse the contents of the statement
  3417. (other than simply counting any L</Placeholders>). The statement is
  3418. passed directly to the database engine, sometimes known as pass-thru
  3419. mode. This has advantages and disadvantages. On the plus side, you can
  3420. access all the functionality of the engine being used. On the downside,
  3421. you're limited if you're using a simple engine, and you need to take extra care if
  3422. writing applications intended to be portable between engines.
  3423.  
  3424. Portable applications should not assume that a new statement can be
  3425. prepared and/or executed while still fetching results from a previous
  3426. statement.
  3427.  
  3428. Some command-line SQL tools use statement terminators, like a semicolon,
  3429. to indicate the end of a statement. Such terminators should not normally
  3430. be used with the DBI.
  3431.  
  3432.  
  3433. =item C<prepare_cached>
  3434.  
  3435.   $sth = $dbh->prepare_cached($statement)
  3436.   $sth = $dbh->prepare_cached($statement, \%attr)
  3437.   $sth = $dbh->prepare_cached($statement, \%attr, $allow_active)
  3438.  
  3439. Like L</prepare> except that the statement handle returned will be
  3440. stored in a hash associated with the C<$dbh>. If another call is made to
  3441. C<prepare_cached> with the same C<$statement> and C<%attr> values, then the
  3442. corresponding cached C<$sth> will be returned without contacting the
  3443. database server.
  3444.  
  3445. Here are some examples of C<prepare_cached>:
  3446.  
  3447.   sub insert_hash {
  3448.     my ($table, $field_values) = @_;
  3449.     my @fields = sort keys %$field_values; # sort required
  3450.     my @values = @{$field_values}{@fields};
  3451.     my $sql = sprintf "insert into %s (%s) values (%s)",
  3452.     $table, join(",", @fields), join(",", ("?")x@fields);
  3453.     my $sth = $dbh->prepare_cached($sql);
  3454.     return $sth->execute(@values);
  3455.   }
  3456.  
  3457.   sub search_hash {
  3458.     my ($table, $field_values) = @_;
  3459.     my @fields = sort keys %$field_values; # sort required
  3460.     my @values = @{$field_values}{@fields};
  3461.     my $qualifier = "";
  3462.     $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields;
  3463.     $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier");
  3464.     return $dbh->selectall_arrayref($sth, {}, @values);
  3465.   }
  3466.  
  3467. I<Caveat emptor:> This caching can be useful in some applications,
  3468. but it can also cause problems and should be used with care. Here
  3469. is a contrived case where caching would cause a significant problem:
  3470.  
  3471.   my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
  3472.   $sth->execute($bar);
  3473.   while (my $data = $sth->fetchrow_hashref) {
  3474.     my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
  3475.     $sth2->execute($data->{bar});
  3476.     while (my $data2 = $sth2->fetchrow_arrayref) {
  3477.       do_stuff(...);
  3478.     }
  3479.   }
  3480.  
  3481. In this example, since both handles are preparing the exact same statement,
  3482. C<$sth2> will not be its own statement handle, but a duplicate of C<$sth>
  3483. returned from the cache. The results will certainly not be what you expect.
  3484. Typically the the inner fetch loop will work normally, fetching all
  3485. the records and terminating when there are no more, but now $sth
  3486. is the same as $sth2 the outer fetch loop will also terminate.
  3487.  
  3488. The C<$allow_active> parameter lets you adjust DBI's behaviour when
  3489. prepare_cached is returning a statement handle that is still active.
  3490. There are three settings:
  3491.  
  3492. =over 4
  3493.  
  3494. B<0>: A warning will be generated, and C<finish> will be called on
  3495. the statement handle before it is returned.  This is the default
  3496. behaviour if C<$allow_active> is not passed.
  3497.  
  3498. B<1>: C<finish> will be called on the statement handle, but the
  3499. warning is suppressed.
  3500.  
  3501. B<2>: DBI will not touch the statement handle before returning it.
  3502. You will need to check C<$sth-E<gt>{Active}> on the returned
  3503. statement handle and deal with it in your own code.
  3504.  
  3505. =back
  3506.  
  3507. Because the cache used by prepare_cached() is keyed by all the
  3508. parameters, including any attributes passed, you can also avoid
  3509. this issue by doing something like:
  3510.  
  3511.   my $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ });
  3512.  
  3513. which will ensure that prepare_cached only returns statements cached
  3514. by that line of code in that source file.
  3515.  
  3516.  
  3517. =item C<commit>
  3518.  
  3519.   $rc  = $dbh->commit     or die $dbh->errstr;
  3520.  
  3521. Commit (make permanent) the most recent series of database changes
  3522. if the database supports transactions and AutoCommit is off.
  3523.  
  3524. If C<AutoCommit> is on, then calling
  3525. C<commit> will issue a "commit ineffective with AutoCommit" warning.
  3526.  
  3527. See also L</Transactions> in the L</FURTHER INFORMATION> section below.
  3528.  
  3529. =item C<rollback>
  3530.  
  3531.   $rc  = $dbh->rollback   or die $dbh->errstr;
  3532.  
  3533. Rollback (undo) the most recent series of uncommitted database
  3534. changes if the database supports transactions and AutoCommit is off.
  3535.  
  3536. If C<AutoCommit> is on, then calling
  3537. C<rollback> will issue a "rollback ineffective with AutoCommit" warning.
  3538.  
  3539. See also L</Transactions> in the L</FURTHER INFORMATION> section below.
  3540.  
  3541. =item C<begin_work>
  3542.  
  3543.   $rc  = $dbh->begin_work   or die $dbh->errstr;
  3544.  
  3545. Enable transactions (by turning C<AutoCommit> off) until the next call
  3546. to C<commit> or C<rollback>. After the next C<commit> or C<rollback>,
  3547. C<AutoCommit> will automatically be turned on again.
  3548.  
  3549. If C<AutoCommit> is already off when C<begin_work> is called then
  3550. it does nothing except return an error. If the driver does not support
  3551. transactions then when C<begin_work> attempts to set C<AutoCommit> off
  3552. the driver will trigger a fatal error.
  3553.  
  3554. See also L</Transactions> in the L</FURTHER INFORMATION> section below.
  3555.  
  3556.  
  3557. =item C<disconnect>
  3558.  
  3559.   $rc = $dbh->disconnect  or warn $dbh->errstr;
  3560.  
  3561. Disconnects the database from the database handle. C<disconnect> is typically only used
  3562. before exiting the program. The handle is of little use after disconnecting.
  3563.  
  3564. The transaction behaviour of the C<disconnect> method is, sadly,
  3565. undefined.  Some database systems (such as Oracle and Ingres) will
  3566. automatically commit any outstanding changes, but others (such as
  3567. Informix) will rollback any outstanding changes.  Applications not
  3568. using C<AutoCommit> should explicitly call C<commit> or C<rollback> before
  3569. calling C<disconnect>.
  3570.  
  3571. The database is automatically disconnected by the C<DESTROY> method if
  3572. still connected when there are no longer any references to the handle.
  3573. The C<DESTROY> method for each driver should implicitly call C<rollback> to
  3574. undo any uncommitted changes. This is vital behaviour to ensure that
  3575. incomplete transactions don't get committed simply because Perl calls
  3576. C<DESTROY> on every object before exiting. Also, do not rely on the order
  3577. of object destruction during "global destruction", as it is undefined.
  3578.  
  3579. Generally, if you want your changes to be commited or rolled back when
  3580. you disconnect, then you should explicitly call L</commit> or L</rollback>
  3581. before disconnecting.
  3582.  
  3583. If you disconnect from a database while you still have active
  3584. statement handles (e.g., SELECT statement handles that may have
  3585. more data to fetch), you will get a warning. The warning may indicate
  3586. that a fetch loop terminated early, perhaps due to an uncaught error.
  3587. To avoid the warning call the C<finish> method on the active handles.
  3588.  
  3589.  
  3590. =item C<ping>
  3591.  
  3592.   $rc = $dbh->ping;
  3593.  
  3594. Attempts to determine, in a reasonably efficient way, if the database
  3595. server is still running and the connection to it is still working.
  3596. Individual drivers should implement this function in the most suitable
  3597. manner for their database engine.
  3598.  
  3599. The current I<default> implementation always returns true without
  3600. actually doing anything. Actually, it returns "C<0 but true>" which is
  3601. true but zero. That way you can tell if the return value is genuine or
  3602. just the default. Drivers should override this method with one that
  3603. does the right thing for their type of database.
  3604.  
  3605. Few applications would have direct use for this method. See the specialized
  3606. Apache::DBI module for one example usage.
  3607.  
  3608.  
  3609. =item C<get_info>
  3610.  
  3611.   $value = $dbh->get_info( $info_type );
  3612.  
  3613. Returns information about the implementation, i.e. driver and data
  3614. source capabilities, restrictions etc. It returns C<undef> for
  3615. unknown or unimplemented information types. For example:
  3616.  
  3617.   $database_version  = $dbh->get_info(  18 ); # SQL_DBMS_VER
  3618.   $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT
  3619.  
  3620. See L</"Standards Reference Information"> for more detailed information
  3621. about the information types and their meanings and possible return values.
  3622.  
  3623. The DBI curently doesn't provide a name to number mapping for the
  3624. information type codes or the results. Applications are expected to use
  3625. the integer values directly, with the name in a comment, or define
  3626. their own named values using something like the L<constant> pragma.
  3627.  
  3628. Because some DBI methods make use of get_info(), drivers are strongly
  3629. encouraged to support I<at least> the following very minimal set
  3630. of information types to ensure the DBI itself works properly:
  3631.  
  3632.  Type  Name                        Example A     Example B
  3633.  ----  --------------------------  ------------  ------------
  3634.    17  SQL_DBMS_NAME               'ACCESS'      'Oracle'
  3635.    18  SQL_DBMS_VER                '03.50.0000'  '08.01.0721'
  3636.    29  SQL_IDENTIFIER_QUOTE_CHAR   '`'           '"'
  3637.    41  SQL_CATALOG_NAME_SEPARATOR  '.'           '@'
  3638.   114  SQL_CATALOG_LOCATION        1             2
  3639.  
  3640. =item C<table_info>
  3641.  
  3642. B<Warning:> This method is experimental and may change.
  3643.  
  3644.   $sth = $dbh->table_info( $catalog, $schema, $table, $type );
  3645.   $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr );
  3646.  
  3647. Returns an active statement handle that can be used to fetch
  3648. information about tables and views that exist in the database.
  3649.  
  3650. The arguments $catalog, $schema and $table may accept search patterns
  3651. according to the database/driver, for example: $table = '%FOO%';
  3652. Remember that the underscore character ('C<_>') is a search pattern
  3653. that means match any character, so 'FOO_%' is the same as 'FOO%'
  3654. and 'FOO_BAR%' will match names like 'FOO1BAR'.
  3655.  
  3656. The value of $type is a comma-separated list of one or more types of
  3657. tables to be returned in the result set. Each value may optionally be
  3658. quoted, e.g.:
  3659.  
  3660.   $type = "TABLE";
  3661.   $type = "'TABLE','VIEW'";
  3662.  
  3663. In addition the following special cases may also be supported by some drivers:
  3664.  
  3665. =over 4
  3666.  
  3667. =item *
  3668. If the value of $catalog is '%' and $schema and $table name
  3669. are empty strings, the result set contains a list of catalog names.
  3670. For example:
  3671.  
  3672.   $sth = $dbh->table_info('%', '', '');
  3673.  
  3674. =item *
  3675. If the value of $schema is '%' and $catalog and $table are empty
  3676. strings, the result set contains a list of schema names.
  3677.  
  3678. =item *
  3679. If the value of $type is '%' and $catalog, $schema, and $table are all
  3680. empty strings, the result set contains a list of table types.
  3681.  
  3682. =back
  3683.  
  3684. If your driver doesn't support one or more of the selection filter
  3685. parameters then you may get back more than you asked for and can
  3686. do the filtering yourself.
  3687.  
  3688. This method can be expensive, and can return a large amount of data.
  3689. (For example, small Oracle installation returns over 2000 rows.)
  3690. So it's a good idea to use the filters to limit the data as much as possible.
  3691.  
  3692. The statement handle returned has at least the following fields in the
  3693. order show below. Other fields, after these, may also be present.
  3694.  
  3695. B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not
  3696. applicable to the data source, which is usually the case. This field
  3697. is empty if not applicable to the table.
  3698.  
  3699. B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value.
  3700. This field is NULL (C<undef>) if not applicable to data source, and
  3701. empty if not applicable to the table.
  3702.  
  3703. B<TABLE_NAME>: Name of the table (or view, synonym, etc).
  3704.  
  3705. B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE",
  3706. "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type
  3707. identifier that is specific to the data
  3708. source.
  3709.  
  3710. B<REMARKS>: A description of the table. May be NULL (C<undef>).
  3711.  
  3712. Note that C<table_info> might not return records for all tables.
  3713. Applications can use any valid table regardless of whether it's
  3714. returned by C<table_info>.
  3715.  
  3716. See also L</tables>, L</"Catalog Methods"> and
  3717. L</"Standards Reference Information">.
  3718.  
  3719. =item C<column_info>
  3720.  
  3721.   $sth = $dbh->column_info( $catalog, $schema, $table, $column );
  3722.  
  3723. Returns an active statement handle that can be used to fetch
  3724. information about columns in specified tables.
  3725.  
  3726. The arguments $schema, $table and $column may accept search patterns
  3727. according to the database/driver, for example: $table = '%FOO%';
  3728.  
  3729. Note: The support for the selection criteria is driver specific. If the
  3730. driver doesn't support one or more of them then you may get back more
  3731. than you asked for and can do the filtering yourself.
  3732.  
  3733. The statement handle returned has at least the following fields in the
  3734. order shown below. Other fields, after these, may also be present.
  3735.  
  3736. B<TABLE_CAT>: The catalog identifier.
  3737. This field is NULL (C<undef>) if not applicable to the data source,
  3738. which is often the case.  This field is empty if not applicable to the
  3739. table.
  3740.  
  3741. B<TABLE_SCHEM>: The schema identifier.
  3742. This field is NULL (C<undef>) if not applicable to the data source,
  3743. and empty if not applicable to the table.
  3744.  
  3745. B<TABLE_NAME>: The table identifier.
  3746. Note: A driver may provide column metadata not only for base tables, but
  3747. also for derived objects like SYNONYMS etc.
  3748.  
  3749. B<COLUMN_NAME>: The column identifier.
  3750.  
  3751. B<DATA_TYPE>: The concise data type code.
  3752.  
  3753. B<TYPE_NAME>: A data source dependent data type name.
  3754.  
  3755. B<COLUMN_SIZE>: The column size.
  3756. This is the maximum length in characters for character data types,
  3757. the number of digits or bits for numeric data types or the length
  3758. in the representation of temporal types.
  3759. See the relevant specifications for detailed information.
  3760.  
  3761. B<BUFFER_LENGTH>: The length in bytes of transferred data.
  3762.  
  3763. B<DECIMAL_DIGITS>: The total number of significant digits to the right of
  3764. the decimal point.
  3765.  
  3766. B<NUM_PREC_RADIX>: The radix for numeric precision.
  3767. The value is 10 or 2 for numeric data types and NULL (C<undef>) if not
  3768. applicable.
  3769.  
  3770. B<NULLABLE>: Indicates if a column can accept NULLs.
  3771. The following values are defined:
  3772.  
  3773.   SQL_NO_NULLS          0
  3774.   SQL_NULLABLE          1
  3775.   SQL_NULLABLE_UNKNOWN  2
  3776.  
  3777. B<REMARKS>: A description of the column.
  3778.  
  3779. B<COLUMN_DEF>: The default value of the column.
  3780.  
  3781. B<SQL_DATA_TYPE>: The SQL data type.
  3782.  
  3783. B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types.
  3784.  
  3785. B<CHAR_OCTET_LENGTH>: The maximum length in bytes of a character or binary
  3786. data type column.
  3787.  
  3788. B<ORDINAL_POSITION>: The column sequence number (starting with 1).
  3789.  
  3790. B<IS_NULLABLE>: Indicates if the column can accept NULLs.
  3791. Possible values are: 'NO', 'YES' and ''.
  3792.  
  3793. SQL/CLI defines the following additional columns:
  3794.  
  3795.   CHAR_SET_CAT
  3796.   CHAR_SET_SCHEM
  3797.   CHAR_SET_NAME
  3798.   COLLATION_CAT
  3799.   COLLATION_SCHEM
  3800.   COLLATION_NAME
  3801.   UDT_CAT
  3802.   UDT_SCHEM
  3803.   UDT_NAME
  3804.   DOMAIN_CAT
  3805.   DOMAIN_SCHEM
  3806.   DOMAIN_NAME
  3807.   SCOPE_CAT
  3808.   SCOPE_SCHEM
  3809.   SCOPE_NAME
  3810.   MAX_CARDINALITY
  3811.   DTD_IDENTIFIER
  3812.   IS_SELF_REF
  3813.  
  3814. Drivers capable of supplying any of those values should do so in
  3815. the corresponding column and supply undef values for the others.
  3816.  
  3817. Drivers wishing to provide extra database/driver specific information
  3818. should do so in extra columns beyond all those listed above, and
  3819. use lowercase field names with the driver-specific prefix (i.e.,
  3820. 'ora_...'). Applications accessing such fields should do so by name
  3821. and not by column number.
  3822.  
  3823. The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME
  3824. and ORDINAL_POSITION.
  3825.  
  3826. Note: There is some overlap with statement attributes (in perl) and
  3827. SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata.
  3828.  
  3829. See also L</"Catalog Methods"> and L</"Standards Reference Information">.
  3830.  
  3831. =item C<primary_key_info>
  3832.  
  3833. B<Warning:> This method is experimental and may change.
  3834.  
  3835.   $sth = $dbh->primary_key_info( $catalog, $schema, $table );
  3836.  
  3837. Returns an active statement handle that can be used to fetch information
  3838. about columns that make up the primary key for a table.
  3839. The arguments don't accept search patterns (unlike table_info()).
  3840.  
  3841. For example:
  3842.  
  3843.   $sth = $dbh->primary_key_info( undef, $user, 'foo' );
  3844.   $data = $sth->fetchall_arrayref;
  3845.  
  3846. Note: The support for the selection criteria, such as $catalog, is
  3847. driver specific.  If the driver doesn't support catalogs and/or
  3848. schemas, it may ignore these criteria.
  3849.  
  3850. The statement handle returned has at least the following fields in the
  3851. order shown below. Other fields, after these, may also be present.
  3852.  
  3853. B<TABLE_CAT>: The catalog identifier.
  3854. This field is NULL (C<undef>) if not applicable to the data source,
  3855. which is often the case.  This field is empty if not applicable to the
  3856. table.
  3857.  
  3858. B<TABLE_SCHEM>: The schema identifier.
  3859. This field is NULL (C<undef>) if not applicable to the data source,
  3860. and empty if not applicable to the table.
  3861.  
  3862. B<TABLE_NAME>: The table identifier.
  3863.  
  3864. B<COLUMN_NAME>: The column identifier.
  3865.  
  3866. B<KEY_SEQ>: The column sequence number (starting with 1).
  3867. Note: This field is named B<ORDINAL_POSITION> in SQL/CLI.
  3868.  
  3869. B<PK_NAME>: The primary key constraint identifier.
  3870. This field is NULL (C<undef>) if not applicable to the data source.
  3871.  
  3872. See also L</"Catalog Methods"> and L</"Standards Reference Information">.
  3873.  
  3874. =item C<primary_key>
  3875.  
  3876.   @key_column_names = $dbh->primary_key( $catalog, $schema, $table );
  3877.  
  3878. Simple interface to the primary_key_info() method. Returns a list of
  3879. the column names that comprise the primary key of the specified table.
  3880. The list is in primary key column sequence order.
  3881.  
  3882. =item C<foreign_key_info>
  3883.  
  3884. B<Warning:> This method is experimental and may change.
  3885.  
  3886.   $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
  3887.                                , $fk_catalog, $fk_schema, $fk_table );
  3888.  
  3889. Returns an active statement handle that can be used to fetch information
  3890. about foreign keys in and/or referencing the specified table(s).
  3891. The arguments don't accept search patterns (unlike table_info()).
  3892.  
  3893. C<$pk_catalog>, C<$pk_schema>, C<$pk_table>
  3894. identify the primary (unique) key table (B<PKT>).
  3895.  
  3896. C<$fk_catalog>, C<$fk_schema>, C<$fk_table>
  3897. identify the foreign key table (B<FKT>).
  3898.  
  3899. If both B<PKT> and B<FKT> are given, the function returns the foreign key, if
  3900. any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>.
  3901. (Note: In SQL/CLI, the result is implementation-defined.)
  3902.  
  3903. If only B<PKT> is given, then the result set contains the primary key
  3904. of that table and all foreign keys that refer to it.
  3905.  
  3906. If only B<FKT> is given, then the result set contains all foreign keys
  3907. in that table and the primary keys to which they refer.
  3908. (Note: In SQL/CLI, the result includes unique keys too.)
  3909.  
  3910. For example:
  3911.  
  3912.   $sth = $dbh->foreign_key_info( undef, $user, 'master');
  3913.   $sth = $dbh->foreign_key_info( undef, undef,   undef , undef, $user, 'detail');
  3914.   $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail');
  3915.  
  3916. Note: The support for the selection criteria, such as C<$catalog>, is
  3917. driver specific.  If the driver doesn't support catalogs and/or
  3918. schemas, it may ignore these criteria.
  3919.  
  3920. The statement handle returned has the following fields in the order shown below.
  3921. Because ODBC never includes unique keys, they define different columns in the
  3922. result set than SQL/CLI. SQL/CLI column names are shown in parentheses.
  3923.  
  3924. B<PKTABLE_CAT    ( UK_TABLE_CAT      )>:
  3925. The primary (unique) key table catalog identifier.
  3926. This field is NULL (C<undef>) if not applicable to the data source,
  3927. which is often the case.  This field is empty if not applicable to the
  3928. table.
  3929.  
  3930. B<PKTABLE_SCHEM  ( UK_TABLE_SCHEM    )>:
  3931. The primary (unique) key table schema identifier.
  3932. This field is NULL (C<undef>) if not applicable to the data source,
  3933. and empty if not applicable to the table.
  3934.  
  3935. B<PKTABLE_NAME   ( UK_TABLE_NAME     )>:
  3936. The primary (unique) key table identifier.
  3937.  
  3938. B<PKCOLUMN_NAME  (UK_COLUMN_NAME    )>:
  3939. The primary (unique) key column identifier.
  3940.  
  3941. B<FKTABLE_CAT    ( FK_TABLE_CAT      )>:
  3942. The foreign key table catalog identifier.
  3943. This field is NULL (C<undef>) if not applicable to the data source,
  3944. which is often the case.  This field is empty if not applicable to the
  3945. table.
  3946.  
  3947. B<FKTABLE_SCHEM  ( FK_TABLE_SCHEM    )>:
  3948. The foreign key table schema identifier.
  3949. This field is NULL (C<undef>) if not applicable to the data source,
  3950. and empty if not applicable to the table.
  3951.  
  3952. B<FKTABLE_NAME   ( FK_TABLE_NAME     )>:
  3953. The foreign key table identifier.
  3954.  
  3955. B<FKCOLUMN_NAME  ( FK_COLUMN_NAME    )>:
  3956. The foreign key column identifier.
  3957.  
  3958. B<KEY_SEQ        ( ORDINAL_POSITION  )>:
  3959. The column sequence number (starting with 1).
  3960.  
  3961. B<UPDATE_RULE    ( UPDATE_RULE       )>:
  3962. The referential action for the UPDATE rule.
  3963. The following codes are defined:
  3964.  
  3965.   CASCADE              0
  3966.   RESTRICT             1
  3967.   SET NULL             2
  3968.   NO ACTION            3
  3969.   SET DEFAULT          4
  3970.  
  3971. B<DELETE_RULE    ( DELETE_RULE       )>:
  3972. The referential action for the DELETE rule.
  3973. The codes are the same as for UPDATE_RULE.
  3974.  
  3975. B<FK_NAME        ( FK_NAME           )>:
  3976. The foreign key name.
  3977.  
  3978. B<PK_NAME        ( UK_NAME           )>:
  3979. The primary (unique) key name.
  3980.  
  3981. B<DEFERRABILITY  ( DEFERABILITY      )>:
  3982. The deferrability of the foreign key constraint.
  3983. The following codes are defined:
  3984.  
  3985.   INITIALLY DEFERRED   5
  3986.   INITIALLY IMMEDIATE  6
  3987.   NOT DEFERRABLE       7
  3988.  
  3989. B<               ( UNIQUE_OR_PRIMARY )>:
  3990. This column is necessary if a driver includes all candidate (i.e. primary and
  3991. alternate) keys in the result set (as specified by SQL/CLI).
  3992. The value of this column is UNIQUE if the foreign key references an alternate
  3993. key and PRIMARY if the foreign key references a primary key, or it
  3994. may be undefined if the driver doesn't have access to the information.
  3995.  
  3996. See also L</"Catalog Methods"> and L</"Standards Reference Information">.
  3997.  
  3998. =item C<tables>
  3999.  
  4000.   @names = $dbh->tables( $catalog, $schema, $table, $type );
  4001.   @names = $dbh->tables;    # deprecated
  4002.  
  4003. Simple interface to table_info(). Returns a list of matching
  4004. table names, possibly including a catalog/schema prefix.
  4005.  
  4006. See L</table_info> for a description of the parameters.
  4007.  
  4008. If C<$dbh-E<gt>get_info(29)> returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR)
  4009. then the table names are constructed and quoted by L</quote_identifier>
  4010. to ensure they are usable even if they contain whitespace or reserved
  4011. words etc.
  4012.  
  4013. =item C<type_info_all>
  4014.  
  4015.   $type_info_all = $dbh->type_info_all;
  4016.  
  4017. Returns a reference to an array which holds information about each data
  4018. type variant supported by the database and driver. The array and its
  4019. contents should be treated as read-only.
  4020.  
  4021. The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs.
  4022. The items following that are references to arrays, one per supported data
  4023. type variant. The leading index hash defines the names and order of the
  4024. fields within the arrays that follow it.
  4025. For example:
  4026.  
  4027.   $type_info_all = [
  4028.     {   TYPE_NAME         => 0,
  4029.     DATA_TYPE         => 1,
  4030.     COLUMN_SIZE       => 2,     # was PRECISION originally
  4031.     LITERAL_PREFIX    => 3,
  4032.     LITERAL_SUFFIX    => 4,
  4033.     CREATE_PARAMS     => 5,
  4034.     NULLABLE          => 6,
  4035.     CASE_SENSITIVE    => 7,
  4036.     SEARCHABLE        => 8,
  4037.     UNSIGNED_ATTRIBUTE=> 9,
  4038.     FIXED_PREC_SCALE  => 10,    # was MONEY originally
  4039.     AUTO_UNIQUE_VALUE => 11,    # was AUTO_INCREMENT originally
  4040.     LOCAL_TYPE_NAME   => 12,
  4041.     MINIMUM_SCALE     => 13,
  4042.     MAXIMUM_SCALE     => 14,
  4043.     NUM_PREC_RADIX    => 15,
  4044.     SQL_DATA_TYPE     => 16,
  4045.     SQL_DATETIME_SUB  => 17,
  4046.     NUM_PREC_RADIX    => 18,
  4047.     INTERVAL_PRECISION=> 19,
  4048.     },
  4049.     [ 'VARCHAR', SQL_VARCHAR,
  4050.     undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
  4051.     ],
  4052.     [ 'INTEGER', SQL_INTEGER,
  4053.     undef,  "", "", undef,0, 0,1,0,0,0,undef,0,  0, 10
  4054.     ],
  4055.   ];
  4056.  
  4057. Note that more than one row may have the same value in the C<DATA_TYPE>
  4058. field if there are different ways to spell the type name and/or there
  4059. are variants of the type with different attributes (e.g., with and
  4060. without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc).
  4061.  
  4062. The rows are ordered by C<DATA_TYPE> first and then by how closely each
  4063. type maps to the corresponding ODBC SQL data type, closest first.
  4064.  
  4065. The meaning of the fields is described in the documentation for
  4066. the L</type_info> method. The index values shown above (e.g.,
  4067. C<NULLABLE =>E<gt> C<6>) are for illustration only. Drivers may define the
  4068. fields with a different order.
  4069.  
  4070. This method is not normally used directly. The L</type_info> method
  4071. provides a more useful interface to the data.
  4072.  
  4073. Even though an 'index' hash is provided, all the field names in the
  4074. index hash defined above will always have the index values defined
  4075. above.  This is defined behaviour so that you don't need to rely on the
  4076. index hash, which is handy because the lettercase of the keys is not
  4077. defined. It is usually uppercase, as show here, but drivers are free to
  4078. return names with any lettercase. Drivers are also free to return extra
  4079. driver-specific columns of information - though it's recommended that
  4080. they start at column index 50 to leave room for expansion of the
  4081. DBI/ODBC specification.
  4082.  
  4083. =item C<type_info>
  4084.  
  4085.   @type_info = $dbh->type_info($data_type);
  4086.  
  4087. Returns a list of hash references holding information about one or more
  4088. variants of $data_type. The list is ordered by C<DATA_TYPE> first and
  4089. then by how closely each type maps to the corresponding ODBC SQL data
  4090. type, closest first.  If called in a scalar context then only the first
  4091. (best) element is returned.
  4092.  
  4093. If $data_type is undefined or C<SQL_ALL_TYPES>, then the list will
  4094. contain hashes for all data type variants supported by the database and driver.
  4095.  
  4096. If $data_type is an array reference then C<type_info> returns the
  4097. information for the I<first> type in the array that has any matches.
  4098.  
  4099. The keys of the hash follow the same letter case conventions as the
  4100. rest of the DBI (see L</Naming Conventions and Name Space>). The
  4101. following items should exist:
  4102.  
  4103. =over 4
  4104.  
  4105. =item TYPE_NAME (string)
  4106.  
  4107. Data type name for use in CREATE TABLE statements etc.
  4108.  
  4109. =item DATA_TYPE (integer)
  4110.  
  4111. SQL data type number.
  4112.  
  4113. =item COLUMN_SIZE (integer)
  4114.  
  4115. For numeric types, this is either the total number of digits (if the
  4116. NUM_PREC_RADIX value is 10) or the total number of bits allowed in the
  4117. column (if NUM_PREC_RADIX is 2).
  4118.  
  4119. For string types, this is the maximum size of the string in bytes.
  4120.  
  4121. For date and interval types, this is the maximum number of characters
  4122. needed to display the value.
  4123.  
  4124. =item LITERAL_PREFIX (string)
  4125.  
  4126. Characters used to prefix a literal. A typical prefix is "C<'>" for characters,
  4127. or possibly "C<0x>" for binary values passed as hexadecimal.  NULL (C<undef>) is
  4128. returned for data types for which this is not applicable.
  4129.  
  4130.  
  4131. =item LITERAL_SUFFIX (string)
  4132.  
  4133. Characters used to suffix a literal. Typically "C<'>" for characters.
  4134. NULL (C<undef>) is returned for data types where this is not applicable.
  4135.  
  4136. =item CREATE_PARAMS (string)
  4137.  
  4138. Parameter names for data type definition. For example, C<CREATE_PARAMS> for a
  4139. C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be
  4140. declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale>
  4141. are integer values.  For a C<VARCHAR> it would be "C<max length>".
  4142. NULL (C<undef>) is returned for data types for which this is not applicable.
  4143.  
  4144. =item NULLABLE (integer)
  4145.  
  4146. Indicates whether the data type accepts a NULL value:
  4147. C<0> or an empty string = no, C<1> = yes, C<2> = unknown.
  4148.  
  4149. =item CASE_SENSITIVE (boolean)
  4150.  
  4151. Indicates whether the data type is case sensitive in collations and
  4152. comparisons.
  4153.  
  4154. =item SEARCHABLE (integer)
  4155.  
  4156. Indicates how the data type can be used in a WHERE clause, as
  4157. follows:
  4158.  
  4159.   0 - Cannot be used in a WHERE clause
  4160.   1 - Only with a LIKE predicate
  4161.   2 - All comparison operators except LIKE
  4162.   3 - Can be used in a WHERE clause with any comparison operator
  4163.  
  4164. =item UNSIGNED_ATTRIBUTE (boolean)
  4165.  
  4166. Indicates whether the data type is unsigned.  NULL (C<undef>) is returned
  4167. for data types for which this is not applicable.
  4168.  
  4169. =item FIXED_PREC_SCALE (boolean)
  4170.  
  4171. Indicates whether the data type always has the same precision and scale
  4172. (such as a money type).  NULL (C<undef>) is returned for data types
  4173. for which
  4174. this is not applicable.
  4175.  
  4176. =item AUTO_UNIQUE_VALUE (boolean)
  4177.  
  4178. Indicates whether a column of this data type is automatically set to a
  4179. unique value whenever a new row is inserted.  NULL (C<undef>) is returned
  4180. for data types for which this is not applicable.
  4181.  
  4182. =item LOCAL_TYPE_NAME (string)
  4183.  
  4184. Localized version of the C<TYPE_NAME> for use in dialog with users.
  4185. NULL (C<undef>) is returned if a localized name is not available (in which
  4186. case C<TYPE_NAME> should be used).
  4187.  
  4188. =item MINIMUM_SCALE (integer)
  4189.  
  4190. The minimum scale of the data type. If a data type has a fixed scale,
  4191. then C<MAXIMUM_SCALE> holds the same value.  NULL (C<undef>) is returned for
  4192. data types for which this is not applicable.
  4193.  
  4194. =item MAXIMUM_SCALE (integer)
  4195.  
  4196. The maximum scale of the data type. If a data type has a fixed scale,
  4197. then C<MINIMUM_SCALE> holds the same value.  NULL (C<undef>) is returned for
  4198. data types for which this is not applicable.
  4199.  
  4200. =item SQL_DATA_TYPE (integer)
  4201.  
  4202. This column is the same as the C<DATA_TYPE> column, except for interval
  4203. and datetime data types.  For interval and datetime data types, the
  4204. C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the
  4205. C<SQL_DATETIME_SUB> field below will return the subcode for the specific
  4206. interval or datetime data type. If this field is NULL, then the driver
  4207. does not support or report on interval or datetime subtypes.
  4208.  
  4209. =item SQL_DATETIME_SUB (integer)
  4210.  
  4211. For interval or datetime data types, where the C<SQL_DATA_TYPE>
  4212. field above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will
  4213. hold the I<subcode> for the specific interval or datetime data type.
  4214. Otherwise it will be NULL (C<undef>).
  4215.  
  4216. Although not mentioned explicitly in the standards, it seems there
  4217. is a simple relationship between these values:
  4218.  
  4219.   DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB
  4220.  
  4221. =item NUM_PREC_RADIX (integer)
  4222.  
  4223. The radix value of the data type. For approximate numeric types,
  4224. C<NUM_PREC_RADIX>
  4225. contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For
  4226. exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds
  4227. the number of decimal digits. NULL (C<undef>) is returned either for data types
  4228. for which this is not applicable or if the driver cannot report this information.
  4229.  
  4230. =item INTERVAL_PRECISION (integer)
  4231.  
  4232. The interval leading precision for interval types. NULL is returned
  4233. either for data types for which this is not applicable or if the driver
  4234. cannot report this information.
  4235.  
  4236. =back
  4237.  
  4238. For example, to find the type name for the fields in a select statement
  4239. you can do:
  4240.  
  4241.   @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }
  4242.  
  4243. Since DBI and ODBC drivers vary in how they map their types into the
  4244. ISO standard types you may need to search for more than one type.
  4245. Here's an example looking for a usable type to store a date:
  4246.  
  4247.   $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] );
  4248.  
  4249. Similarly, to more reliably find a type to store small integers, you could
  4250. use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc.
  4251.  
  4252. See also L</"Standards Reference Information">.
  4253.  
  4254.  
  4255. =item C<quote>
  4256.  
  4257.   $sql = $dbh->quote($value);
  4258.   $sql = $dbh->quote($value, $data_type);
  4259.  
  4260. Quote a string literal for use as a literal value in an SQL statement,
  4261. by escaping any special characters (such as quotation marks)
  4262. contained within the string and adding the required type of outer
  4263. quotation marks.
  4264.  
  4265.   $sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
  4266.                 $dbh->quote("Don't");
  4267.  
  4268. For most database types, quote would return C<'Don''t'> (including the
  4269. outer quotation marks).
  4270.  
  4271. An undefined C<$value> value will be returned as the string C<NULL> (without
  4272. single quotation marks) to match how NULLs are represented in SQL.
  4273.  
  4274. If C<$data_type> is supplied, it is used to try to determine the required
  4275. quoting behaviour by using the information returned by L</type_info>.
  4276. As a special case, the standard numeric types are optimized to return
  4277. C<$value> without calling C<type_info>.
  4278.  
  4279. Quote will probably I<not> be able to deal with all possible input
  4280. (such as binary data or data containing newlines), and is not related in
  4281. any way with escaping or quoting shell meta-characters. The quote()
  4282. method should I<not> be used with L</"Placeholders and Bind Values">.
  4283.  
  4284. =item C<quote_identifier>
  4285.  
  4286.   $sql = $dbh->quote_identifier( $name );
  4287.   $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr );
  4288.  
  4289. Quote an identifier (table name etc.) for use in an SQL statement,
  4290. by escaping any special characters (such as double quotation marks)
  4291. it contains and adding the required type of outer quotation marks.
  4292.  
  4293. Undefined names are ignored and the remainder are quoted and then
  4294. joined together, typically with a dot (C<.>) character. For example:
  4295.  
  4296.   $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' );
  4297.  
  4298. would, for most database types, return C<"Her schema"."My table">
  4299. (including all the double quotation marks).
  4300.  
  4301. If three names are supplied then the first is assumed to be a
  4302. catalog name and special rules may be applied based on what L</get_info>
  4303. returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114).
  4304. For example, for Oracle:
  4305.  
  4306.   $id = $dbh->quote_identifier( 'link', 'schema', 'table' );
  4307.  
  4308. would return C<"schema"."table"@"link">.
  4309.  
  4310. =item C<take_imp_data>
  4311.  
  4312.   $imp_data = $dbh->take_imp_data;
  4313.  
  4314. Leaves the $dbh in an almost dead, zombie-like, state and returns
  4315. a binary string of raw implementation data from the driver which
  4316. describes the current database connection. Effectively it detaches
  4317. the underlying database API connection data from the DBI handle.
  4318. After calling take_imp_data(), all other methods except C<DESTROY>
  4319. will generate a warning and return undef.
  4320.  
  4321. Why would you want to do this? You don't, forget I even mentioned it.
  4322. Unless, that is, you're implementing something advanced like a
  4323. multi-threaded connection pool.
  4324.  
  4325. The returned $imp_data can be passed as a C<dbi_imp_data> attribute
  4326. to a later connect() call, even in a separate thread in the same
  4327. process, where the driver can use it to 'adopt' the existing
  4328. connection that the implementation data was taken from.
  4329.  
  4330. Some things to keep in mind...
  4331.  
  4332. B<*> the $imp_data holds the only reference to the underlying
  4333. database API connection data. That connection is still 'live' and
  4334. won't be cleaned up properly unless the $imp_data is used to create
  4335. a new $dbh which can then disconnect() normally.
  4336.  
  4337. B<*> using the same $imp_data to create more than one other new
  4338. $dbh at a time may well lead to unpleasant problems. Don't do that.
  4339.  
  4340. The C<take_imp_data> method was added in DBI 1.36.
  4341.  
  4342. =back
  4343.  
  4344.  
  4345. =head2 Database Handle Attributes
  4346.  
  4347. This section describes attributes specific to database handles.
  4348.  
  4349. Changes to these database handle attributes do not affect any other
  4350. existing or future database handles.
  4351.  
  4352. Attempting to set or get the value of an unknown attribute is fatal,
  4353. except for private driver-specific attributes (which all have names
  4354. starting with a lowercase letter).
  4355.  
  4356. Example:
  4357.  
  4358.   $h->{AutoCommit} = ...;    # set/write
  4359.   ... = $h->{AutoCommit};    # get/read
  4360.  
  4361. =over 4
  4362.  
  4363. =item C<AutoCommit>  (boolean)
  4364.  
  4365. If true, then database changes cannot be rolled-back (undone).  If false,
  4366. then database changes automatically occur within a "transaction", which
  4367. must either be committed or rolled back using the C<commit> or C<rollback>
  4368. methods.
  4369.  
  4370. Drivers should always default to C<AutoCommit> mode (an unfortunate
  4371. choice largely forced on the DBI by ODBC and JDBC conventions.)
  4372.  
  4373. Attempting to set C<AutoCommit> to an unsupported value is a fatal error.
  4374. This is an important feature of the DBI. Applications that need
  4375. full transaction behaviour can set C<$dbh-E<gt>{AutoCommit} = 0> (or
  4376. set C<AutoCommit> to 0 via L</connect>)
  4377. without having to check that the value was assigned successfully.
  4378.  
  4379. For the purposes of this description, we can divide databases into three
  4380. categories:
  4381.  
  4382.   Databases which don't support transactions at all.
  4383.   Databases in which a transaction is always active.
  4384.   Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>).
  4385.  
  4386. B<* Databases which don't support transactions at all>
  4387.  
  4388. For these databases, attempting to turn C<AutoCommit> off is a fatal error.
  4389. C<commit> and C<rollback> both issue warnings about being ineffective while
  4390. C<AutoCommit> is in effect.
  4391.  
  4392. B<* Databases in which a transaction is always active>
  4393.  
  4394. These are typically mainstream commercial relational databases with
  4395. "ANSI standard" transaction behaviour.
  4396. If C<AutoCommit> is off, then changes to the database won't have any
  4397. lasting effect unless L</commit> is called (but see also
  4398. L</disconnect>). If L</rollback> is called then any changes since the
  4399. last commit are undone.
  4400.  
  4401. If C<AutoCommit> is on, then the effect is the same as if the DBI
  4402. called C<commit> automatically after every successful database
  4403. operation. So calling C<commit> or C<rollback> explicitly while
  4404. C<AutoCommit> is on would be ineffective because the changes would
  4405. have already been commited.
  4406.  
  4407. Changing C<AutoCommit> from off to on will trigger a L</commit>.
  4408.  
  4409. For databases which don't support a specific auto-commit mode, the
  4410. driver has to commit each statement automatically using an explicit
  4411. C<COMMIT> after it completes successfully (and roll it back using an
  4412. explicit C<ROLLBACK> if it fails).  The error information reported to the
  4413. application will correspond to the statement which was executed, unless
  4414. it succeeded and the commit or rollback failed.
  4415.  
  4416. B<* Databases in which a transaction must be explicitly started>
  4417.  
  4418. For these databases, the intention is to have them act like databases in
  4419. which a transaction is always active (as described above).
  4420.  
  4421. To do this, the driver will automatically begin an explicit transaction
  4422. when C<AutoCommit> is turned off, or after a L</commit> or
  4423. L</rollback> (or when the application issues the next database
  4424. operation after one of those events).
  4425.  
  4426. In this way, the application does not have to treat these databases
  4427. as a special case.
  4428.  
  4429. See L</commit>, L</disconnect> and L</Transactions> for other important
  4430. notes about transactions.
  4431.  
  4432.  
  4433. =item C<Driver>  (handle)
  4434.  
  4435. Holds the handle of the parent driver. The only recommended use for this
  4436. is to find the name of the driver using:
  4437.  
  4438.   $dbh->{Driver}->{Name}
  4439.  
  4440.  
  4441. =item C<Name>  (string)
  4442.  
  4443. Holds the "name" of the database. Usually (and recommended to be) the
  4444. same as the "C<dbi:DriverName:...>" string used to connect to the database,
  4445. but with the leading "C<dbi:DriverName:>" removed.
  4446.  
  4447.  
  4448. =item C<Statement>  (string, read-only)
  4449.  
  4450. Returns the statement string passed to the most recent L</prepare> method
  4451. called in this database handle, even if that method failed. This is especially
  4452. useful where C<RaiseError> is enabled and the exception handler checks $@
  4453. and sees that a 'prepare' method call failed.
  4454.  
  4455.  
  4456. =item C<RowCacheSize>  (integer)
  4457.  
  4458. A hint to the driver indicating the size of the local row cache that the
  4459. application would like the driver to use for future C<SELECT> statements.
  4460. If a row cache is not implemented, then setting C<RowCacheSize> is ignored
  4461. and getting the value returns C<undef>.
  4462.  
  4463. Some C<RowCacheSize> values have special meaning, as follows:
  4464.  
  4465.   0 - Automatically determine a reasonable cache size for each C<SELECT>
  4466.   1 - Disable the local row cache
  4467.  >1 - Cache this many rows
  4468.  <0 - Cache as many rows that will fit into this much memory for each C<SELECT>.
  4469.  
  4470. Note that large cache sizes may require a very large amount of memory
  4471. (I<cached rows * maximum size of row>). Also, a large cache will cause
  4472. a longer delay not only for the first fetch, but also whenever the
  4473. cache needs refilling.
  4474.  
  4475. See also the L</RowsInCache> statement handle attribute.
  4476.  
  4477. =item C<Username>  (string)
  4478.  
  4479. Returns the username used to connect to the database.
  4480.  
  4481.  
  4482. =back
  4483.  
  4484.  
  4485. =head1 DBI STATEMENT HANDLE OBJECTS
  4486.  
  4487. This section lists the methods and attributes associated with DBI
  4488. statement handles.
  4489.  
  4490. =head2 Statement Handle Methods
  4491.  
  4492. The DBI defines the following methods for use on DBI statement handles:
  4493.  
  4494. =over 4
  4495.  
  4496. =item C<bind_param>
  4497.  
  4498.   $rc = $sth->bind_param($p_num, $bind_value)  or die $sth->errstr;
  4499.   $rv = $sth->bind_param($p_num, $bind_value, \%attr)     or ...
  4500.   $rv = $sth->bind_param($p_num, $bind_value, $bind_type) or ...
  4501.  
  4502. The C<bind_param> method takes a copy of $bind_value and associates it
  4503. (binds it) with a placeholder, identified by $p_num, embedded in
  4504. the prepared statement. Placeholders are indicated with question
  4505. mark character (C<?>). For example:
  4506.  
  4507.   $dbh->{RaiseError} = 1;        # save having to check each method call
  4508.   $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?");
  4509.   $sth->bind_param(1, "John%");  # placeholders are numbered from 1
  4510.   $sth->execute;
  4511.   DBI::dump_results($sth);
  4512.  
  4513. See L</"Placeholders and Bind Values"> for more information.
  4514.  
  4515.  
  4516. B<Data Types for Placeholders>
  4517.  
  4518. The C<\%attr> parameter can be used to hint at the data type the
  4519. placeholder should have. Typically, the driver is only interested in
  4520. knowing if the placeholder should be bound as a number or a string.
  4521.  
  4522.   $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
  4523.  
  4524. As a short-cut for the common case, the data type can be passed
  4525. directly, in place of the C<\%attr> hash reference. This example is
  4526. equivalent to the one above:
  4527.  
  4528.   $sth->bind_param(1, $value, SQL_INTEGER);
  4529.  
  4530. The C<TYPE> value indicates the standard (non-driver-specific) type for
  4531. this parameter. To specify the driver-specific type, the driver may
  4532. support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>.
  4533.  
  4534. The SQL_INTEGER and other related constants can be imported using
  4535.  
  4536.   use DBI qw(:sql_types);
  4537.  
  4538. See L</"DBI Constants"> for more information.
  4539.  
  4540. The data type for a placeholder cannot be changed after the first
  4541. C<bind_param> call. In fact the whole \%attr parameter is 'sticky'
  4542. in the sense that a driver only needs to consider the \%attr parameter
  4543. for the first call, for a given $sth and parameter. After that the driver
  4544. may ignore the \%attr parameter for that placeholder.
  4545.  
  4546. Perl only has string and number scalar data types. All database types
  4547. that aren't numbers are bound as strings and must be in a format the
  4548. database will understand.
  4549.  
  4550. As an alternative to specifying the data type in the C<bind_param> call,
  4551. you can let the driver pass the value as the default type (C<VARCHAR>).
  4552. You can then use an SQL function to convert the type within the statement.
  4553. For example:
  4554.  
  4555.   INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
  4556.  
  4557. The C<CONVERT> function used here is just an example. The actual function
  4558. and syntax will vary between different databases and is non-portable.
  4559.  
  4560. See also L</"Placeholders and Bind Values"> for more information.
  4561.  
  4562.  
  4563. =item C<bind_param_inout>
  4564.  
  4565.   $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len)  or die $sth->errstr;
  4566.   $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr)     or ...
  4567.   $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ...
  4568.  
  4569. This method acts like L</bind_param>, but also enables values to be
  4570. updated by the statement. The statement is typically
  4571. a call to a stored procedure. The C<$bind_value> must be passed as a
  4572. reference to the actual value to be used.
  4573.  
  4574. Note that unlike L</bind_param>, the C<$bind_value> variable is not
  4575. copied when C<bind_param_inout> is called. Instead, the value in the
  4576. variable is read at the time L</execute> is called.
  4577.  
  4578. The additional C<$max_len> parameter specifies the minimum amount of
  4579. memory to allocate to C<$bind_value> for the new value. If the value
  4580. returned from the database is too
  4581. big to fit, then the execution should fail. If unsure what value to use,
  4582. pick a generous length, i.e., a length larger than the longest value that would ever be
  4583. returned.  The only cost of using a larger value than needed is wasted memory.
  4584.  
  4585. It is expected that few drivers will support this method. The only
  4586. driver currently known to do so is DBD::Oracle (DBD::ODBC may support
  4587. it in a future release). Therefore it should not be used for database
  4588. independent applications.
  4589.  
  4590. Undefined values or C<undef> are used to indicate null values.
  4591. See also L</"Placeholders and Bind Values"> for more information.
  4592.  
  4593.  
  4594. =item C<bind_param_array>
  4595.  
  4596.   $rc = $sth->bind_param_array($p_num, $array_ref_or_value)
  4597.   $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr)
  4598.   $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type)
  4599.  
  4600. The C<bind_param_array> method is used to bind an array of values
  4601. to a placeholder embedded in the prepared statement which is to be executed
  4602. with L</execute_array>. For example:
  4603.  
  4604.   $dbh->{RaiseError} = 1;        # save having to check each method call
  4605.   $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)");
  4606.   $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]);
  4607.   $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]);
  4608.   $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row
  4609.   $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  4610.  
  4611. The C<%attr> ($bind_type) argument is the same as defined for L</bind_param>.
  4612. Refer to L</bind_param> for general details on using placeholders.
  4613.  
  4614. (Note that bind_param_array() can I<not> be used to expand a
  4615. placeholder into a list of values for a statement like "SELECT foo
  4616. WHERE bar IN (?)".  A placeholder can only ever represent one value
  4617. per execution.)
  4618.  
  4619. Each array bound to the statement must have the same number of
  4620. elements.  Some drivers may define a method attribute to relax this
  4621. safety check.
  4622.  
  4623. Scalar values, including C<undef>, may also be bound by
  4624. C<bind_param_array>. In which case the same value will be used for each
  4625. L</execute> call. Driver-specific implementations may behave
  4626. differently, e.g., when binding to a stored procedure call, some
  4627. databases may permit mixing scalars and arrays as arguments.
  4628.  
  4629. The default implementation provided by DBI (for drivers that have
  4630. not implemented array binding) is to iteratively call L</execute> for
  4631. each parameter tuple provided in the bound arrays.  Drivers may
  4632. provide more optimized implementations using whatever bulk operation
  4633. support the database API provides. The default driver behaviour should 
  4634. match the default DBI behaviour, but always consult your driver
  4635. documentation as there may be driver specific issues to consider.
  4636.  
  4637. Note that the default implementation currently only supports non-data
  4638. returning statements (insert, update, but not select). Also,
  4639. C<bind_param_array> and L</bind_param> cannot be mixed in the same
  4640. statement execution, and C<bind_param_array> must be used with
  4641. L</execute_array>; using C<bind_param_array> will have no effect
  4642. for L</execute>.
  4643.  
  4644. The C<bind_param_array> method was added in DBI 1.22.
  4645.  
  4646. =item C<execute>
  4647.  
  4648.   $rv = $sth->execute                or die $sth->errstr;
  4649.   $rv = $sth->execute(@bind_values)  or die $sth->errstr;
  4650.  
  4651. Perform whatever processing is necessary to execute the prepared
  4652. statement.  An C<undef> is returned if an error occurs.  A successful
  4653. C<execute> always returns true regardless of the number of rows affected,
  4654. even if it's zero (see below). It is always important to check the
  4655. return status of C<execute> (and most other DBI methods) for errors
  4656. if you're not using L</RaiseError>.
  4657.  
  4658. For a I<non>-C<SELECT> statement, C<execute> returns the number of rows
  4659. affected, if known. If no rows were affected, then C<execute> returns
  4660. "C<0E0>", which Perl will treat as 0 but will regard as true. Note that it
  4661. is I<not> an error for no rows to be affected by a statement. If the
  4662. number of rows affected is not known, then C<execute> returns -1.
  4663.  
  4664. For C<SELECT> statements, execute simply "starts" the query within the
  4665. database engine. Use one of the fetch methods to retrieve the data after
  4666. calling C<execute>.  The C<execute> method does I<not> return the number of
  4667. rows that will be returned by the query (because most databases can't
  4668. tell in advance), it simply returns a true value.
  4669.  
  4670. If any arguments are given, then C<execute> will effectively call
  4671. L</bind_param> for each value before executing the statement.  Values
  4672. bound in this way are usually treated as C<SQL_VARCHAR> types unless
  4673. the driver can determine the correct type (which is rare), or unless
  4674. C<bind_param> (or C<bind_param_inout>) has already been used to
  4675. specify the type.
  4676.  
  4677. If execute() is called on a statement handle that's still active
  4678. ($sth->{Active} is true) then it should effectively call finish()
  4679. to tidy up the previous execution results before starting this new
  4680. execution.
  4681.  
  4682. =item C<execute_array>
  4683.  
  4684.   $rv = $sth->execute_array(\%attr) or die $sth->errstr;
  4685.   $rv = $sth->execute_array(\%attr, @bind_values)  or die $sth->errstr;
  4686.  
  4687. Execute the prepared statement once for each parameter tuple
  4688. (group of values) provided either in the @bind_values, or by prior
  4689. calls to L</bind_param_array>, or via a reference passed in \%attr.
  4690.  
  4691. The execute_array() method returns the number of tuples executed,
  4692. or C<undef> if an error occured. Like execute(), a successful
  4693. execute_array() always returns true regardless of the number of
  4694. tuples executed, even if it's zero.  See the C<ArrayTupleStatus>
  4695. attribute below for how to determine the execution status for each
  4696. tuple.
  4697.  
  4698. Bind values for the tuples to be executed may be supplied by an
  4699. C<ArrayTupleFetch> attribute, or else in the C<@bind_values> argument,
  4700. or else by prior calls to L</bind_param_array>.
  4701.  
  4702. The C<ArrayTupleFetch> attribute can be used to specify a reference
  4703. to a subroutine that will be called to provide the bind values for
  4704. each tuple execution. The subroutine should return an reference to
  4705. an array which contains the appropriate number of bind values, or
  4706. return an undef if there is no more data to execute.
  4707.  
  4708. As a convienience, the C<ArrayTupleFetch> attribute can also be
  4709. used to specify a statement handle. In which case the fetchrow_arrayref()
  4710. method will be called on the given statement handle in order to
  4711. provide the bind values for each tuple execution.
  4712.  
  4713. The values specified via bind_param_array() or the @bind_values
  4714. parameter may be either scalars, or arrayrefs.  If any C<@bind_values>
  4715. are given, then C<execute_array> will effectively call L</bind_param_array>
  4716. for each value before executing the statement.  Values bound in
  4717. this way are usually treated as C<SQL_VARCHAR> types unless the
  4718. driver can determine the correct type (which is rare), or unless
  4719. C<bind_param>, C<bind_param_inout>, C<bind_param_array>, or
  4720. C<bind_param_inout_array> has already been used to specify the type.
  4721. See L</bind_param_array> for details.
  4722.  
  4723. The mandatory C<ArrayTupleStatus> attribute is used to specify a
  4724. reference to an array which will receive the execute status of each
  4725. executed parameter tuple.
  4726.  
  4727. For tuples which are successfully executed, the element at the same
  4728. ordinal position in the status array is the resulting rowcount.
  4729. If the execution of a tuple causes an error, then the corresponding
  4730. status array element will be set to a reference to an array containing
  4731. the error code and error string set by the failed execution.
  4732.  
  4733. If B<any> tuple execution returns an error, C<execute_array> will
  4734. return C<undef>. In that case, the application should inspect the
  4735. status array to determine which parameter tuples failed.
  4736. Some databases may not continue executing tuples beyond the first
  4737. failure. In this case the status array will either hold fewer
  4738. elements, or the elements beyond the failure will be undef.
  4739.  
  4740. If all parameter tuples are successfully executed, C<execute_array>
  4741. returns the number tuples executed.  If no tuples were executed,
  4742. then execute_array() returns "C<0E0>", just like execute() does,
  4743. which Perl will treat as 0 but will regard as true.
  4744.  
  4745. For example:
  4746.  
  4747.   $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)");
  4748.   my $tuples = $sth->execute_array(
  4749.       { ArrayTupleStatus => \my @tuple_status },
  4750.       \@first_names,
  4751.       \@last_names,
  4752.   );
  4753.   if ($tuples) {
  4754.       print "Successfully inserted $tuples records\n";
  4755.   }
  4756.   else {
  4757.       for my $tuple (0..@last_names-1) {
  4758.           my $status = $tuple_status[$tuple];
  4759.           $status = [0, "Skipped"] unless defined $status;
  4760.           next unless ref $status;
  4761.           printf "Failed to insert (%s, %s): %s\n",
  4762.               $first_names[$tuple], $last_names[$tuple], $status->[1];
  4763.       }
  4764.   }
  4765.  
  4766. Support for data returning statements, i.e., select, is driver-specific
  4767. and subject to change. At present, the default implementation
  4768. provided by DBI only supports non-data returning statements.
  4769.  
  4770. Transaction semantics when using array binding are driver and
  4771. database specific.  If C<AutoCommit> is on, the default DBI
  4772. implementation will cause each parameter tuple to be inidividually
  4773. committed (or rolled back in the event of an error). If C<AutoCommit>
  4774. is off, the application is responsible for explicitly committing
  4775. the entire set of bound parameter tuples.  Note that different
  4776. drivers and databases may have different behaviours when some
  4777. parameter tuples cause failures. In some cases, the driver or
  4778. database may automatically rollback the effect of all prior parameter
  4779. tuples that succeeded in the transaction; other drivers or databases
  4780. may retain the effect of prior successfully executed parameter
  4781. tuples. Be sure to check your driver and database for its specific
  4782. behaviour.
  4783.  
  4784. Note that, in general, performance will usually be better with
  4785. C<AutoCommit> turned off, and using explicit C<commit> after each
  4786. C<execute_array> call.
  4787.  
  4788. The C<execute_array> method was added in DBI 1.22, and ArrayTupleFetch
  4789. was added in 1.36.
  4790.  
  4791. =item C<execute_for_fetch>
  4792.  
  4793.   $rc = $sth->execute_for_fetch($fetch_tuple_sub);
  4794.   $rc = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
  4795.  
  4796. The execute_for_fetch() method is used to perform bulk operations
  4797. and is most often used via the execute_array() method, not directly.
  4798.  
  4799. The fetch subroutine, referenced by $fetch_tuple_sub, is expected
  4800. to return a reference to an array (known as a 'tuple') or undef.
  4801.  
  4802. The execute_for_fetch() method calls $fetch_tuple_sub, without any
  4803. parameters, until it returns a false value. Each tuple returned is
  4804. used to provide bind values for an $sth->execute(@$tuple) call.
  4805.  
  4806. The number of tuples executed is returned, regardless of the success
  4807. or failure of those executions. Use tuple_status to check.
  4808.  
  4809. If \@tuple_status is passed then the execute_for_fetch method uses
  4810. it to return status information. The tuple_status array holds one
  4811. element per tuple. If the corresponding execute() did not fail then
  4812. the element holds the return value from execute(), which is typically
  4813. a row count. If the execute() did fail then the element holds a
  4814. reference to an array containing ($sth->err, $sth->errstr, $sth->state).
  4815.  
  4816. Although each tuple returned by $fetch_tuple_sub is effectively used
  4817. to call $sth->execute(@$tuple_array_ref) the exact timing may vary.
  4818. Drivers are free to accumulate sets of tuples to pass to the
  4819. database server in bulk group operations for more efficient execution.
  4820. However, the $fetch_tuple_sub is specifically allowed to return
  4821. the same array reference each time.
  4822.  
  4823. For example:
  4824.  
  4825.   my $sel = $dbh1->prepare("select foo, bar from table1");
  4826.   $sel->execute;
  4827.   my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)");
  4828.   $ins->execute;
  4829.   my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref };
  4830.   my @tuple_status;
  4831.   $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
  4832.   my @errors = grep { ref $_ } @tuple_status;
  4833.  
  4834. The C<execute_for_fetch> method was added in DBI 1.38.
  4835.  
  4836.  
  4837. =item C<fetchrow_arrayref>
  4838.  
  4839.   $ary_ref = $sth->fetchrow_arrayref;
  4840.   $ary_ref = $sth->fetch;    # alias
  4841.  
  4842. Fetches the next row of data and returns a reference to an array
  4843. holding the field values.  Null fields are returned as C<undef>
  4844. values in the array.
  4845. This is the fastest way to fetch data, particularly if used with
  4846. C<$sth-E<gt>bind_columns>.
  4847.  
  4848. If there are no more rows or if an error occurs, then C<fetchrow_arrayref>
  4849. returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the
  4850. C<RaiseError> attribute) to discover if the C<undef> returned was due to an
  4851. error.
  4852.  
  4853. Note that the same array reference is returned for each fetch, so don't
  4854. store the reference and then use it after a later fetch.  Also, the
  4855. elements of the array are also reused for each row, so take care if you
  4856. want to take a reference to an element. See also L</bind_columns>.
  4857.  
  4858. =item C<fetchrow_array>
  4859.  
  4860.  @ary = $sth->fetchrow_array;
  4861.  
  4862. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  4863. and returns it as a list containing the field values.  Null fields
  4864. are returned as C<undef> values in the list.
  4865.  
  4866. If there are no more rows or if an error occurs, then C<fetchrow_array>
  4867. returns an empty list. You should check C<$sth-E<gt>err> afterwards (or use
  4868. the C<RaiseError> attribute) to discover if the empty list returned was
  4869. due to an error.
  4870.  
  4871. If called in a scalar context for a statement handle that has more
  4872. than one column, it is undefined whether the driver will return
  4873. the value of the first column or the last. So don't do that.
  4874. Also, in a scalar context, an C<undef> is returned if there are no
  4875. more rows or if an error occurred. That C<undef> can't be distinguished
  4876. from an C<undef> returned because the first field value was NULL.
  4877. For these reasons you should exercise some caution if you use
  4878. C<fetchrow_array> in a scalar context.
  4879.  
  4880. =item C<fetchrow_hashref>
  4881.  
  4882.  $hash_ref = $sth->fetchrow_hashref;
  4883.  $hash_ref = $sth->fetchrow_hashref($name);
  4884.  
  4885. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  4886. and returns it as a reference to a hash containing field name and field
  4887. value pairs.  Null fields are returned as C<undef> values in the hash.
  4888.  
  4889. If there are no more rows or if an error occurs, then C<fetchrow_hashref>
  4890. returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the
  4891. C<RaiseError> attribute) to discover if the C<undef> returned was due to an
  4892. error.
  4893.  
  4894. The optional C<$name> parameter specifies the name of the statement handle
  4895. attribute. For historical reasons it defaults to "C<NAME>", however using either
  4896. "C<NAME_lc>" or "C<NAME_uc>" is recomended for portability.
  4897.  
  4898. The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If
  4899. more than one field has the same name, there will only be one entry in
  4900. the returned hash for those fields.
  4901.  
  4902. Because of the extra work C<fetchrow_hashref> and Perl have to perform, it
  4903. is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>.
  4904.  
  4905. Currently, a new hash reference is returned for each row.  I<This will
  4906. change> in the future to return the same hash ref each time, so don't
  4907. rely on the current behaviour.
  4908.  
  4909.  
  4910. =item C<fetchall_arrayref>
  4911.  
  4912.   $tbl_ary_ref = $sth->fetchall_arrayref;
  4913.   $tbl_ary_ref = $sth->fetchall_arrayref( $slice );
  4914.   $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows  );
  4915.  
  4916. The C<fetchall_arrayref> method can be used to fetch all the data to be
  4917. returned from a prepared and executed statement handle. It returns a
  4918. reference to an array that contains one reference per row.
  4919.  
  4920. If there are no rows to return, C<fetchall_arrayref> returns a reference
  4921. to an empty array. If an error occurs, C<fetchall_arrayref> returns the
  4922. data fetched thus far, which may be none.  You should check C<$sth-E<gt>err>
  4923. afterwards (or use the C<RaiseError> attribute) to discover if the data is
  4924. complete or was truncated due to an error.
  4925.  
  4926. If $slice is an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref>
  4927. to fetch each row as an array ref. If the $slice array is not empty
  4928. then it is used as a slice to select individual columns by perl array
  4929. index number (starting at 0, unlike column and parameter numbers which
  4930. start at 1).
  4931.  
  4932. With no parameters, or if $slice is undefined, C<fetchall_arrayref>
  4933. acts as if passed an empty array ref.
  4934.  
  4935. If $slice is a hash reference, C<fetchall_arrayref> uses L</fetchrow_hashref>
  4936. to fetch each row as a hash reference. If the $slice hash is empty then
  4937. fetchrow_hashref() is simply called in a tight loop and the keys in the hashes
  4938. have whatever name lettercase is returned by default from fetchrow_hashref.
  4939. (See L</FetchHashKeyName> attribute.) If the $slice hash is not
  4940. empty, then it is used as a slice to select individual columns by
  4941. name.  The values of the hash should be set to 1.  The key names
  4942. of the returned hashes match the letter case of the names in the
  4943. parameter hash, regardless of the L</FetchHashKeyName> attribute.
  4944.  
  4945. For example, to fetch just the first column of every row:
  4946.  
  4947.   $tbl_ary_ref = $sth->fetchall_arrayref([0]);
  4948.  
  4949. To fetch the second to last and last column of every row:
  4950.  
  4951.   $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]);
  4952.  
  4953. To fetch all fields of every row as a hash ref:
  4954.  
  4955.   $tbl_ary_ref = $sth->fetchall_arrayref({});
  4956.  
  4957. To fetch only the fields called "foo" and "bar" of every row as a hash ref
  4958. (with keys named "foo" and "BAR"):
  4959.  
  4960.   $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 });
  4961.  
  4962. The first two examples return a reference to an array of array refs.
  4963. The third and forth return a reference to an array of hash refs.
  4964.  
  4965. If $max_rows is defined and greater than or equal to zero then it
  4966. is used to limit the number of rows fetched before returning.
  4967. fetchall_arrayref() can then be called again to fetch more rows.
  4968. This is especially useful when you need the better performance of
  4969. fetchall_arrayref() but don't have enough memory to fetch and return
  4970. all the rows in one go. Here's an example:
  4971.  
  4972.   my $rows = []; # cache for batches of rows
  4973.   while( my $row = ( shift(@$rows) || # get row from cache, or reload cache:
  4974.                      shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]) )
  4975.   ) {
  4976.     ...
  4977.   }
  4978.  
  4979. That is the fastest way to fetch and process lots of rows using the DBI.
  4980.  
  4981.  
  4982. =item C<fetchall_hashref>
  4983.  
  4984.   $hash_ref = $sth->fetchall_hashref($key_field);
  4985.  
  4986. The C<fetchall_hashref> method can be used to fetch all the data to be
  4987. returned from a prepared and executed statement handle. It returns a
  4988. reference to a hash that contains, at most, one entry per row.
  4989.  
  4990. If there are no rows to return, C<fetchall_hashref> returns a reference
  4991. to an empty hash. If an error occurs, C<fetchall_hashref> returns the
  4992. data fetched thus far, which may be none.  You should check
  4993. C<$sth-E<gt>err> afterwards (or use the C<RaiseError> attribute) to
  4994. discover if the data is complete or was truncated due to an error.
  4995.  
  4996. The $key_field parameter provides the name of the field that holds the
  4997. value to be used for the key for the returned hash.  For example:
  4998.  
  4999.   $dbh->{FetchHashKeyName} = 'NAME_lc';
  5000.   $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE");
  5001.   $hash_ref = $sth->fetchall_hashref('id');
  5002.   print "Name for id 42 is $hash_ref->{42}->{name}\n";
  5003.  
  5004. The $key_field parameter can also be specified as an integer column
  5005. number (counting from 1).  If $key_field doesn't match any column in
  5006. the statement, as a name first then as a number, then an error is
  5007. returned.
  5008.  
  5009. This method is normally used only where the key field value for each
  5010. row is unique.  If multiple rows are returned with the same value for
  5011. the key field then later rows overwrite earlier ones.
  5012.  
  5013.  
  5014. =item C<finish>
  5015.  
  5016.   $rc  = $sth->finish;
  5017.  
  5018. Indicate that no more data will be fetched from this statement handle
  5019. before it is either executed again or destroyed.  The C<finish> method
  5020. is rarely needed, and frequently overused, but can sometimes be
  5021. helpful in a few very specific situations to allow the server to free
  5022. up resources (such as sort buffers).
  5023.  
  5024. When all the data has been fetched from a C<SELECT> statement, the
  5025. driver should automatically call C<finish> for you. So you should
  5026. I<not> normally need to call it explicitly I<except> when you know
  5027. that you've not fetched all the data from a statement handle.
  5028. The most common example is when you only want to fetch one row,
  5029. but in that case the C<selectrow_*> methods are usually better anyway.
  5030. Adding calls to C<finish> after each fetch loop is a common mistake,
  5031. don't do it, it can mask genuine problems like uncaught fetch errors.
  5032.  
  5033. Consider a query like:
  5034.  
  5035.   SELECT foo FROM table WHERE bar=? ORDER BY foo
  5036.  
  5037. where you want to select just the first (smallest) "foo" value from a
  5038. very large table. When executed, the database server will have to use
  5039. temporary buffer space to store the sorted rows. If, after executing
  5040. the handle and selecting one row, the handle won't be re-executed for
  5041. some time and won't be destroyed, the C<finish> method can be used to tell
  5042. the server that the buffer space can be freed.
  5043.  
  5044. Calling C<finish> resets the L</Active> attribute for the statement.  It
  5045. may also make some statement handle attributes (such as C<NAME> and C<TYPE>)
  5046. unavailable if they have not already been accessed (and thus cached).
  5047.  
  5048. The C<finish> method does not affect the transaction status of the
  5049. database connection.  It has nothing to do with transactions. It's mostly an
  5050. internal "housekeeping" method that is rarely needed.
  5051. See also L</disconnect> and the L</Active> attribute.
  5052.  
  5053. The C<finish> method should have been called C<cancel_select>.
  5054.  
  5055.  
  5056. =item C<rows>
  5057.  
  5058.   $rv = $sth->rows;
  5059.  
  5060. Returns the number of rows affected by the last row affecting command,
  5061. or -1 if the number of rows is not known or not available.
  5062.  
  5063. Generally, you can only rely on a row count after a I<non>-C<SELECT>
  5064. C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or
  5065. after fetching all the rows of a C<SELECT> statement.
  5066.  
  5067. For C<SELECT> statements, it is generally not possible to know how many
  5068. rows will be returned except by fetching them all.  Some drivers will
  5069. return the number of rows the application has fetched so far, but
  5070. others may return -1 until all rows have been fetched.  So use of the
  5071. C<rows> method or C<$DBI::rows> with C<SELECT> statements is not
  5072. recommended.
  5073.  
  5074. One alternative method to get a row count for a C<SELECT> is to execute a
  5075. "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your
  5076. query and then fetch the row count from that.
  5077.  
  5078.  
  5079. =item C<bind_col>
  5080.  
  5081.   $rc = $sth->bind_col($column_number, \$var_to_bind);
  5082.   $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr );
  5083.  
  5084. Binds an output column (field) of a C<SELECT> statement to a Perl variable.
  5085. See C<bind_columns> below for an example.  Note that column numbers count
  5086. up from 1.
  5087.  
  5088. Whenever a row is fetched from the database, the corresponding Perl
  5089. variable is automatically updated. There is no need to fetch and assign
  5090. the values manually.  The binding is performed at a very low level
  5091. using Perl aliasing so there is no extra copying taking place.  This
  5092. makes using bound variables very efficient.
  5093.  
  5094. For maximum portability between drivers, C<bind_col> should be called after
  5095. C<execute>. This restriction may be removed in a later version of the DBI.
  5096.  
  5097. You do not need to bind output columns in order to fetch data, but it
  5098. can be useful for some applications which need either maximum performance
  5099. or greater clarity of code.  The L</bind_param> method
  5100. performs a similar but opposite function for input variables.
  5101.  
  5102. =item C<bind_columns>
  5103.  
  5104.   $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
  5105.  
  5106. Calls L</bind_col> for each column of the C<SELECT> statement.
  5107. The C<bind_columns> method will die if the number of references does not
  5108. match the number of fields.
  5109.  
  5110. For maximum portability between drivers, C<bind_columns> should be called
  5111. after C<execute>.
  5112.  
  5113. For example:
  5114.  
  5115.   $dbh->{RaiseError} = 1; # do this, or check every call for errors
  5116.   $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
  5117.   $sth->execute;
  5118.   my ($region, $sales);
  5119.  
  5120.   # Bind Perl variables to columns:
  5121.   $rv = $sth->bind_columns(\$region, \$sales);
  5122.  
  5123.   # you can also use Perl's \(...) syntax (see perlref docs):
  5124.   #     $sth->bind_columns(\($region, $sales));
  5125.  
  5126.   # Column binding is the most efficient way to fetch data
  5127.   while ($sth->fetch) {
  5128.       print "$region: $sales\n";
  5129.   }
  5130.  
  5131. For compatibility with old scripts, the first parameter will be
  5132. ignored if it is C<undef> or a hash reference.
  5133.  
  5134. Here's a more fancy example that binds columns to the values I<inside>
  5135. a hash (thanks to H.Merijn Brand):
  5136.  
  5137.   $sth->execute;
  5138.   my %row;
  5139.   $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } ));
  5140.   while ($sth->fetch) {
  5141.       print "$row{region}: $row{sales}\n";
  5142.   }
  5143.  
  5144.  
  5145. =item C<dump_results>
  5146.  
  5147.   $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
  5148.  
  5149. Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and
  5150. prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep>
  5151. (default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35.
  5152.  
  5153. This method is designed as a handy utility for prototyping and
  5154. testing queries. Since it uses L</neat_list> to
  5155. format and edit the string for reading by humans, it is not recomended
  5156. for data transfer applications.
  5157.  
  5158. =back
  5159.  
  5160.  
  5161. =head2 Statement Handle Attributes
  5162.  
  5163. This section describes attributes specific to statement handles. Most
  5164. of these attributes are read-only.
  5165.  
  5166. Changes to these statement handle attributes do not affect any other
  5167. existing or future statement handles.
  5168.  
  5169. Attempting to set or get the value of an unknown attribute is fatal,
  5170. except for private driver specific attributes (which all have names
  5171. starting with a lowercase letter).
  5172.  
  5173. Example:
  5174.  
  5175.   ... = $h->{NUM_OF_FIELDS};    # get/read
  5176.  
  5177. Note that some drivers cannot provide valid values for some or all of
  5178. these attributes until after C<$sth-E<gt>execute> has been called.
  5179.  
  5180. See also L</finish> to learn more about the effect it
  5181. may have on some attributes.
  5182.  
  5183. =over 4
  5184.  
  5185. =item C<NUM_OF_FIELDS>  (integer, read-only)
  5186.  
  5187. Number of fields (columns) in the data the prepared statement may return.
  5188. Statements that don't return rows of data, like C<DELETE> and C<CREATE>
  5189. set C<NUM_OF_FIELDS> to 0.
  5190.  
  5191.  
  5192. =item C<NUM_OF_PARAMS>  (integer, read-only)
  5193.  
  5194. The number of parameters (placeholders) in the prepared statement.
  5195. See SUBSTITUTION VARIABLES below for more details.
  5196.  
  5197.  
  5198. =item C<NAME>  (array-ref, read-only)
  5199.  
  5200. Returns a reference to an array of field names for each column. The
  5201. names may contain spaces but should not be truncated or have any
  5202. trailing space. Note that the names have the letter case (upper, lower
  5203. or mixed) as returned by the driver being used. Portable applications
  5204. should use L</NAME_lc> or L</NAME_uc>.
  5205.  
  5206.   print "First column name: $sth->{NAME}->[0]\n";
  5207.  
  5208. =item C<NAME_lc>  (array-ref, read-only)
  5209.  
  5210. Like L</NAME> but always returns lowercase names.
  5211.  
  5212. =item C<NAME_uc>  (array-ref, read-only)
  5213.  
  5214. Like L</NAME> but always returns uppercase names.
  5215.  
  5216. =item C<NAME_hash>  (hash-ref, read-only)
  5217.  
  5218. =item C<NAME_lc_hash>  (hash-ref, read-only)
  5219.  
  5220. =item C<NAME_uc_hash>  (hash-ref, read-only)
  5221.  
  5222. The C<NAME_hash>, C<NAME_lc_hash>, and C<NAME_uc_hash> attributes
  5223. return column name information as a reference to a hash.
  5224.  
  5225. The keys of the hash are the names of the columns.  The letter case of
  5226. the keys corresponds to the letter case returned by the C<NAME>,
  5227. C<NAME_lc>, and C<NAME_uc> attributes respectively (as described above).
  5228.  
  5229. The value of each hash entry is the perl index number of the
  5230. corresponding column (counting from 0). For example:
  5231.  
  5232.   $sth = $dbh->prepare("select Id, Name from table");
  5233.   $sth->execute;
  5234.   @row = $sth->fetchrow_array;
  5235.   print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n";
  5236.  
  5237.  
  5238. =item C<TYPE>  (array-ref, read-only)
  5239.  
  5240. Returns a reference to an array of integer values for each
  5241. column. The value indicates the data type of the corresponding column.
  5242.  
  5243. The values correspond to the international standards (ANSI X3.135
  5244. and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific
  5245. types that don't exactly match standard types should generally return
  5246. the same values as an ODBC driver supplied by the makers of the
  5247. database. That might include private type numbers in ranges the vendor
  5248. has officially registered with the ISO working group:
  5249.  
  5250.   ftp://sqlstandards.org/SC32/SQL_Registry/
  5251.  
  5252. Where there's no vendor-supplied ODBC driver to be compatible with,
  5253. the DBI driver can use type numbers in the range that is now
  5254. officially reserved for use by the DBI: -9999 to -9000.
  5255.  
  5256. All possible values for C<TYPE> should have at least one entry in the
  5257. output of the C<type_info_all> method (see L</type_info_all>).
  5258.  
  5259. =item C<PRECISION>  (array-ref, read-only)
  5260.  
  5261. Returns a reference to an array of integer values for each
  5262. column.  For non-numeric columns, the value generally refers to either
  5263. the maximum length or the defined length of the column.  For numeric
  5264. columns, the value refers to the maximum number of significant digits
  5265. used by the data type (without considering a sign character or decimal
  5266. point).  Note that for floating point types (REAL, FLOAT, DOUBLE), the
  5267. "display size" can be up to 7 characters greater than the precision.
  5268. (for the sign + decimal point + the letter E + a sign + 2 or 3 digits).
  5269.  
  5270. =item C<SCALE>  (array-ref, read-only)
  5271.  
  5272. Returns a reference to an array of integer values for each column.
  5273. NULL (C<undef>) values indicate columns where scale is not applicable.
  5274.  
  5275. =item C<NULLABLE>  (array-ref, read-only)
  5276.  
  5277. Returns a reference to an array indicating the possibility of each
  5278. column returning a null.  Possible values are C<0>
  5279. (or an empty string) = no, C<1> = yes, C<2> = unknown.
  5280.  
  5281.   print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
  5282.  
  5283.  
  5284. =item C<CursorName>  (string, read-only)
  5285.  
  5286. Returns the name of the cursor associated with the statement handle, if
  5287. available. If not available or if the database driver does not support the
  5288. C<"where current of ..."> SQL syntax, then it returns C<undef>.
  5289.  
  5290.  
  5291. =item C<Database>  (dbh, read-only)
  5292.  
  5293. Returns the parent $dbh of the statement handle.
  5294.  
  5295.  
  5296. =item C<ParamValues>  (hash ref, read-only)
  5297.  
  5298. Returns a reference to a hash containing the values currently bound
  5299. to placeholders.  The keys of the hash are the 'names' of the
  5300. placeholders, typically integers starting at 1.  Returns undef if
  5301. not supported by the driver.
  5302.  
  5303. See L</ShowErrorStatement> for an example of how this is used.
  5304.  
  5305. If the driver supports C<ParamValues> but no values have been bound
  5306. yet then the driver should return a hash with placeholders names
  5307. in the keys but all the values undef, but some drivers may return
  5308. a ref to an empty hash.
  5309.  
  5310. It is possible that the values in the hash returned by C<ParamValues>
  5311. are not exactly the same as those passed to bind_param() or execute().
  5312. The driver may have modified the values in some way based on the
  5313. TYPE the value was bound with. For example a floating point value
  5314. bound as an SQL_INTEGER type may be returned as an integer.
  5315.  
  5316. It is also possible that the keys in the hash returned by C<ParamValues>
  5317. are not exactly the same as those implied by the prepared statement.
  5318. For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>'
  5319. where N is a sequence number starting at 1.
  5320.  
  5321. The C<ParamValues> attribute was added in DBI 1.28.
  5322.  
  5323.  
  5324. =item C<Statement>  (string, read-only)
  5325.  
  5326. Returns the statement string passed to the L</prepare> method.
  5327.  
  5328.  
  5329. =item C<RowsInCache>  (integer, read-only)
  5330.  
  5331. If the driver supports a local row cache for C<SELECT> statements, then
  5332. this attribute holds the number of un-fetched rows in the cache. If the
  5333. driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch
  5334. rows on execute, whereas others wait till the first fetch.
  5335.  
  5336. See also the L</RowCacheSize> database handle attribute.
  5337.  
  5338. =back
  5339.  
  5340. =head1 OTHER METHODS
  5341.  
  5342. =over 4
  5343.  
  5344. =item C<install_method>
  5345.  
  5346.     DBD::Foo::db->install_method($method_name, \%attr);
  5347.  
  5348. Installs the driver-private method named by $method_name into the
  5349. DBI method dispatcher so it can be called directly, avoiding the
  5350. need to use the func() method.
  5351.  
  5352. It is called as a static method on the driver class to which the
  5353. method belongs. The method name must begin with the corresponding
  5354. registered driver-private prefix. For example, for DBD::Oracle
  5355. $method_name must being with 'C<ora_>', and for DBD::AnyData it
  5356. must begin with 'C<ad_>'.
  5357.  
  5358. The attributes can be used to provide fine control over how the DBI
  5359. dispatcher handles the dispatching of the method. However, at this
  5360. point, it's undocumented and very liable to change. (Volunteers to
  5361. polish up and document the interface are very welcome to get in
  5362. touch via dbi-dev@perl.org)
  5363.  
  5364. Methods installed using install_method default to the standard error
  5365. handling behaviour for DBI methods: clearing err and errstr before
  5366. calling the method, and checking for errors to trigger RaiseError
  5367. etc. on return. This differs from the default behaviour of func().
  5368.  
  5369. Note for driver authors: The DBD::Foo::xx->install_method call won't
  5370. work until the class-hierarchy has been setup. Normally the DBI
  5371. looks after that just after the driver is loaded. This means
  5372. install_method() can't be called at the time the driver is loaded
  5373. unless the class-hierarchy is set up first. The way to do that is
  5374. to call the setup_driver() method:
  5375.  
  5376.     DBI->setup_driver('DBD::Foo');
  5377.  
  5378. before using install_method().
  5379.  
  5380.  
  5381. =back
  5382.  
  5383. =head1 FURTHER INFORMATION
  5384.  
  5385. =head2 Catalog Methods
  5386.  
  5387. An application can retrieve metadata information from the DBMS by issuing
  5388. appropriate queries on the views of the Information Schema. Unfortunately,
  5389. C<INFORMATION_SCHEMA> views are seldom supported by the DBMS.
  5390. Special methods (catalog methods) are available to return result sets
  5391. for a small but important portion of that metadata:
  5392.  
  5393.   column_info
  5394.   foreign_key_info
  5395.   primary_key_info
  5396.   table_info
  5397.  
  5398. All catalog methods accept arguments in order to restrict the result sets.
  5399. Passing C<undef> to an optional argument does not constrain the search for
  5400. that argument.
  5401. However, an empty string ('') is treated as a regular search criteria
  5402. and will only match an empty value.
  5403.  
  5404. B<Note>: SQL/CLI and ODBC differ in the handling of empty strings. An
  5405. empty string will not restrict the result set in SQL/CLI.
  5406.  
  5407. Most arguments in the catalog methods accept only I<ordinary values>, e.g.
  5408. the arguments of C<primary_key_info()>.
  5409. Such arguments are treated as a literal string, i.e. the case is significant
  5410. and quote characters are taken literally.
  5411.  
  5412. Some arguments in the catalog methods accept I<search patterns> (strings
  5413. containing '_' and/or '%'), e.g. the C<$table> argument of C<column_info()>.
  5414. Passing '%' is equivalent to leaving the argument C<undef>.
  5415.  
  5416. B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers.
  5417. Passing such a value to a search pattern argument may return more rows than
  5418. expected!
  5419. To include pattern characters as literals, they must be preceded by an
  5420. escape character which can be achieved with
  5421.  
  5422.   $esc = $dbh->get_info( 14 );  # SQL_SEARCH_PATTERN_ESCAPE
  5423.   $search_pattern =~ s/([_%])/$esc$1/g;
  5424.  
  5425. The ODBC and SQL/CLI specifications define a way to change the default
  5426. behaviour described above: All arguments (except I<list value arguments>)
  5427. are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is
  5428. set to C<SQL_TRUE>.
  5429. I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their
  5430. body (the string within the quotes) is interpreted literally.
  5431. I<Unquoted identifiers> are compared in UPPERCASE.
  5432.  
  5433. The DBI (currently) does not support the C<SQL_ATTR_METADATA_ID> attribute,
  5434. i.e. it behaves like an ODBC driver where C<SQL_ATTR_METADATA_ID> is set to
  5435. C<SQL_FALSE>.
  5436.  
  5437.  
  5438. =head2 Transactions
  5439.  
  5440. Transactions are a fundamental part of any robust database system. They
  5441. protect against errors and database corruption by ensuring that sets of
  5442. related changes to the database take place in atomic (indivisible,
  5443. all-or-nothing) units.
  5444.  
  5445. This section applies to databases that support transactions and where
  5446. C<AutoCommit> is off.  See L</AutoCommit> for details of using C<AutoCommit>
  5447. with various types of databases.
  5448.  
  5449. The recommended way to implement robust transactions in Perl
  5450. applications is to use C<RaiseError> and S<C<eval { ... }>>
  5451. (which is very fast, unlike S<C<eval "...">>). For example:
  5452.  
  5453.   $dbh->{AutoCommit} = 0;  # enable transactions, if possible
  5454.   $dbh->{RaiseError} = 1;
  5455.   eval {
  5456.       foo(...)        # do lots of work here
  5457.       bar(...)        # including inserts
  5458.       baz(...)        # and updates
  5459.       $dbh->commit;   # commit the changes if we get this far
  5460.   };
  5461.   if ($@) {
  5462.       warn "Transaction aborted because $@";
  5463.       # now rollback to undo the incomplete changes
  5464.       # but do it in an eval{} as it may also fail
  5465.       eval { $dbh->rollback };
  5466.       # add other application on-error-clean-up code here
  5467.   }
  5468.  
  5469. If the C<RaiseError> attribute is not set, then DBI calls would need to be
  5470. manually checked for errors, typically like this:
  5471.  
  5472.   $h->method(@args) or die $h->errstr;
  5473.  
  5474. With C<RaiseError> set, the DBI will automatically C<die> if any DBI method
  5475. call on that handle (or a child handle) fails, so you don't have to
  5476. test the return value of each method call. See L</RaiseError> for more
  5477. details.
  5478.  
  5479. A major advantage of the C<eval> approach is that the transaction will be
  5480. properly rolled back if I<any> code (not just DBI calls) in the inner
  5481. application dies for any reason. The major advantage of using the
  5482. C<$h-E<gt>{RaiseError}> attribute is that all DBI calls will be checked
  5483. automatically. Both techniques are strongly recommended.
  5484.  
  5485. After calling C<commit> or C<rollback> many drivers will not let you
  5486. fetch from a previously active C<SELECT> statement handle that's a child
  5487. of the same database handle. A typical way round this is to connect the
  5488. the database twice and use one connection for C<SELECT> statements.
  5489.  
  5490. See L</AutoCommit> and L</disconnect> for other important information
  5491. about transactions.
  5492.  
  5493.  
  5494. =head2 Handling BLOB / LONG / Memo Fields
  5495.  
  5496. Many databases support "blob" (binary large objects), "long", or similar
  5497. datatypes for holding very long strings or large amounts of binary
  5498. data in a single field. Some databases support variable length long
  5499. values over 2,000,000,000 bytes in length.
  5500.  
  5501. Since values of that size can't usually be held in memory, and because
  5502. databases can't usually know in advance the length of the longest long
  5503. that will be returned from a C<SELECT> statement (unlike other data
  5504. types), some special handling is required.
  5505.  
  5506. In this situation, the value of the C<$h-E<gt>{LongReadLen}> attribute is used
  5507. to determine how much buffer space to allocate when fetching such
  5508. fields.  The C<$h-E<gt>{LongTruncOk}> attribute is used to determine how to
  5509. behave if a fetched value can't fit into the buffer.
  5510.  
  5511. When trying to insert long or binary values, placeholders should be used
  5512. since there are often limits on the maximum size of an C<INSERT>
  5513. statement and the L</quote> method generally can't cope with binary
  5514. data.  See L</Placeholders and Bind Values>.
  5515.  
  5516.  
  5517. =head2 Simple Examples
  5518.  
  5519. Here's a complete example program to select and fetch some data:
  5520.  
  5521.   my $data_source = "dbi::DriverName:db_name";
  5522.   my $dbh = DBI->connect($data_source, $user, $password)
  5523.       or die "Can't connect to $data_source: $DBI::errstr";
  5524.  
  5525.   my $sth = $dbh->prepare( q{
  5526.           SELECT name, phone
  5527.           FROM mytelbook
  5528.   }) or die "Can't prepare statement: $DBI::errstr";
  5529.  
  5530.   my $rc = $sth->execute
  5531.       or die "Can't execute statement: $DBI::errstr";
  5532.  
  5533.   print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
  5534.   print "Field names: @{ $sth->{NAME} }\n";
  5535.  
  5536.   while (($name, $phone) = $sth->fetchrow_array) {
  5537.       print "$name: $phone\n";
  5538.   }
  5539.   # check for problems which may have terminated the fetch early
  5540.   die $sth->errstr if $sth->err;
  5541.  
  5542.   $dbh->disconnect;
  5543.  
  5544. Here's a complete example program to insert some data from a file.
  5545. (This example uses C<RaiseError> to avoid needing to check each call).
  5546.  
  5547.   my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, {
  5548.       RaiseError => 1, AutoCommit => 0
  5549.   });
  5550.  
  5551.   my $sth = $dbh->prepare( q{
  5552.       INSERT INTO table (name, phone) VALUES (?, ?)
  5553.   });
  5554.  
  5555.   open FH, "<phone.csv" or die "Unable to open phone.csv: $!";
  5556.   while (<FH>) {
  5557.       chomp;
  5558.       my ($name, $phone) = split /,/;
  5559.       $sth->execute($name, $phone);
  5560.   }
  5561.   close FH;
  5562.  
  5563.   $dbh->commit;
  5564.   $dbh->disconnect;
  5565.  
  5566. Here's how to convert fetched NULLs (undefined values) into empty strings:
  5567.  
  5568.   while($row = $sth->fetchrow_arrayref) {
  5569.     # this is a fast and simple way to deal with nulls:
  5570.     foreach (@$row) { $_ = '' unless defined }
  5571.     print "@$row\n";
  5572.   }
  5573.  
  5574. The C<q{...}> style quoting used in these examples avoids clashing with
  5575. quotes that may be used in the SQL statement. Use the double-quote like
  5576. C<qq{...}> operator if you want to interpolate variables into the string.
  5577. See L<perlop/"Quote and Quote-like Operators"> for more details.
  5578.  
  5579.  
  5580. =head2 Threads and Thread Safety
  5581.  
  5582. Perl 5.7 and later support a new threading model called iThreads.
  5583. (The old "5.005 style" threads are not supported by the DBI.)
  5584.  
  5585. In the iThreads model each thread has it's own copy of the perl
  5586. interpreter.  When a new thread is created the original perl
  5587. interpreter is 'cloned' to create a new copy for the new thread.
  5588.  
  5589. If the DBI and drivers are loaded and handles created before the
  5590. thread is created then it will get a cloned copy of the DBI, the
  5591. drivers and the handles.
  5592.  
  5593. However, the internal pointer data within the handles will refer
  5594. to the DBI and drivers in the original interpreter. Using those
  5595. handles in the new interpreter thread is not safe, so the DBI detects
  5596. this and croaks on any method call using handles that don't belong
  5597. to the current thread (except for DESTROY).
  5598.  
  5599. Because of this (possibly temporary) restriction, newly created
  5600. threads must make their own connctions to the database. Handles
  5601. can't be shared across threads.
  5602.  
  5603. But BEWARE, some underlying database APIs (the code the DBD driver
  5604. uses to talk to the database, often supplied by the database vendor)
  5605. are not thread safe. If it's not thread safe, then allowing more
  5606. than one thread to enter the code at the same time may cause
  5607. subtle/serious problems. In some cases allowing more than
  5608. one thread to enter the code, even if I<not> at the same time,
  5609. can cause problems. You have been warned.
  5610.  
  5611. Using DBI with perl threads is not yet recommended for production
  5612. environments.
  5613.  
  5614.  
  5615. =head2 Signal Handling and Canceling Operations
  5616.  
  5617. The first thing to say is that signal handling in Perl is currently
  5618. I<not> safe. There is always a small risk of Perl crashing and/or
  5619. core dumping when, or after, handling a signal.  (The risk was reduced
  5620. with 5.004_04 but is still present.)
  5621.  
  5622. The two most common uses of signals in relation to the DBI are for
  5623. canceling operations when the user types Ctrl-C (interrupt), and for
  5624. implementing a timeout using C<alarm()> and C<$SIG{ALRM}>.
  5625.  
  5626. To assist in implementing these operations, the DBI provides a C<cancel>
  5627. method for statement handles. The C<cancel> method should abort the current
  5628. operation and is designed to be called from a signal handler.
  5629.  
  5630. However, it must be stressed that: a) few drivers implement this at
  5631. the moment (the DBI provides a default method that just returns C<undef>);
  5632. and b) even if implemented, there is still a possibility that the statement
  5633. handle, and possibly the parent database handle, will not be usable
  5634. afterwards.
  5635.  
  5636. If C<cancel> returns true, then it has successfully
  5637. invoked the database engine's own cancel function.  If it returns false,
  5638. then C<cancel> failed. If it returns C<undef>, then the database
  5639. engine does not have cancel implemented.
  5640.  
  5641.  
  5642. =head2 Subclassing the DBI
  5643.  
  5644. DBI can be subclassed and extended just like any other object
  5645. oriented module.  Before we talk about how to do that, it's important
  5646. to be clear about how the DBI classes and how they work together.
  5647.  
  5648. By default C<$dbh = DBI-E<gt>connect(...)> returns a $dbh blessed
  5649. into the C<DBI::db> class.  And the C<$dbh-E<gt>prepare> method
  5650. returns an $sth blessed into the C<DBI::st> class (actually it
  5651. simply changes the last four characters of the calling handle class
  5652. to be C<::st>).
  5653.  
  5654. The leading 'C<DBI>' is known as the 'root class' and the extra
  5655. 'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want
  5656. to subclass the DBI you'll need to put your overriding methods into
  5657. the appropriate classes.  For example, if you want to use a root class
  5658. of C<MySubDBI> and override the do(), prepare() and execute() methods,
  5659. then your do() and prepare() methods should be in the C<MySubDBI::db>
  5660. class and the execute() method should be in the C<MySubDBI::st> class.
  5661.  
  5662. To setup the inheritance hierarchy the @ISA variable in C<MySubDBI::db>
  5663. should include C<DBI::db> and the @ISA variable in C<MySubDBI::st>
  5664. should include C<DBI::st>.  The C<MySubDBI> root class itself isn't
  5665. currently used for anything visible and so, apart from setting @ISA
  5666. to include C<DBI>, it should be left empty.
  5667.  
  5668. So, having put your overriding methods into the right classes, and
  5669. setup the inheritance hierarchy, how do you get the DBI to use them?
  5670. You have two choices, either a static method call using the name
  5671. of your subclass:
  5672.  
  5673.   $dbh = MySubDBI->connect(...);
  5674.  
  5675. or specifying a C<RootClass> attribute:
  5676.  
  5677.   $dbh = DBI->connect(..., { RootClass => 'MySubDBI' });
  5678.  
  5679. The only difference between the two is that using an explicit
  5680. RootClass attribute will make the DBI automatically attempt to load
  5681. a module by that name if the class doesn't exist.
  5682.  
  5683. If both forms are used then the attribute takes precedence.
  5684.  
  5685. When subclassing is being used then, after a successful new
  5686. connect, the DBI->connect method automatically calls:
  5687.  
  5688.   $dbh->connected($dsn, $user, $pass, \%attr);
  5689.  
  5690. The default method does nothing. The call is made just to simplify
  5691. any post-connection setup that your subclass may want to perform.
  5692. If your subclass supplies a connected method, it should be part of the
  5693. MySubDBI::db package.
  5694.  
  5695. Here's a brief example of a DBI subclass.  A more thorough example
  5696. can be found in t/subclass.t in the DBI distribution.
  5697.  
  5698.   package MySubDBI;
  5699.  
  5700.   use strict;
  5701.  
  5702.   use DBI;
  5703.   use vars qw(@ISA);
  5704.   @ISA = qw(DBI);
  5705.  
  5706.   package MySubDBI::db;
  5707.   use vars qw(@ISA);
  5708.   @ISA = qw(DBI::db);
  5709.  
  5710.   sub prepare {
  5711.     my ($dbh, @args) = @_;
  5712.     my $sth = $dbh->SUPER::prepare(@args)
  5713.         or return;
  5714.     $sth->{private_mysubdbi_info} = { foo => 'bar' };
  5715.     return $sth;
  5716.   }
  5717.  
  5718.   package MySubDBI::st;
  5719.   use vars qw(@ISA);
  5720.   @ISA = qw(DBI::st);
  5721.  
  5722.   sub fetch {
  5723.     my ($sth, @args) = @_;
  5724.     my $row = $sth->SUPER::fetch(@args)
  5725.         or return;
  5726.     do_something_magical_with_row_data($row)
  5727.         or return $sth->set_err(1234, "The magic failed", undef, "fetch");
  5728.     return $row;
  5729.   }
  5730.  
  5731. When calling a SUPER::method that returns a handle, be careful to
  5732. check the return value before trying to do other things with it in
  5733. your overridden method. This is especially important if you want
  5734. to set a hash attribute on the handle, as Perl's autovivification
  5735. will bite you by (in)conveniently creating an unblessed hashref,
  5736. which your method will then return with usually baffling results
  5737. later on.  It's best to check right after the call and return undef
  5738. immediately on error, just like DBI would and just like the example
  5739. above.
  5740.  
  5741. If your method needs to record an error it should call the set_err()
  5742. method with the error code and error string, as shown in the example
  5743. above. The error code and error string will be recorded in the
  5744. handle and available via C<$h-E<gt>err> and C<$DBI::errstr> etc.
  5745. The set_err() method always returns an undef or empty list as
  5746. approriate. Since your method should nearly always return an undef
  5747. or empty list as soon as an error is detected it's handy to simply
  5748. return what set_err() returns, as shown in the example above.
  5749.  
  5750. If the handle has C<RaiseError>, C<PrintError>, or C<HandleError>
  5751. etc. set then the set_err() method will honour them. This means
  5752. that if C<RaiseError> is set then set_err() won't return in the
  5753. normal way but will 'throw an exception' that can be caught with
  5754. an C<eval> block.
  5755.  
  5756. You can stash private data into DBI handles
  5757. via C<$h-E<gt>{private_..._*}>.  See the entry under L</ATTRIBUTES
  5758. COMMON TO ALL HANDLES> for info and important caveats.
  5759.  
  5760.  
  5761. =head1 DEBUGGING
  5762.  
  5763. In addition to the L</trace> method, you can enable the same trace
  5764. information by setting the C<DBI_TRACE> environment variable before
  5765. starting Perl.
  5766.  
  5767. On Unix-like systems using a Bourne-like shell, you can do this easily
  5768. on the command line:
  5769.  
  5770.   DBI_TRACE=2 perl your_test_script.pl
  5771.  
  5772. If C<DBI_TRACE> is set to a non-numeric value, then it is assumed to
  5773. be a file name and the trace level will be set to 2 with all trace
  5774. output appended to that file. If the name begins with a number
  5775. followed by an equal sign (C<=>), then the number and the equal sign are
  5776. stripped off from the name, and the number is used to set the trace
  5777. level. For example:
  5778.  
  5779.   DBI_TRACE=1=dbitrace.log perl your_test_script.pl
  5780.  
  5781. See also the L</trace> method.
  5782.  
  5783. It can sometimes be handy to compare trace files from two different
  5784. runs of the same script. However using a tool like C<diff> doesn't work
  5785. well because the trace file is full of object addresses that may
  5786. differ each run. Here's a handy little command to strip those out:
  5787.  
  5788.  perl -pe 's/\b0x[\da-f]{6,}/0xNNNN/gi; s/\b[\da-f]{6,}/<long number>/gi'
  5789.  
  5790.  
  5791. =head1 DBI ENVIRONMENT VARIABLES
  5792.  
  5793. The DBI module recognizes a number of environment variables, but most of
  5794. them should not be used most of the time.
  5795. It is better to be explicit about what you are doing to avoid the need
  5796. for environment variables, especially in a web serving system where web
  5797. servers are stingy about which environment variables are available.
  5798.  
  5799. =head2 DBI_DSN
  5800.  
  5801. The DBI_DSN environment variable is used by DBI->connect if you do not
  5802. specify a data source when you issue the connect.
  5803. It should have a format such as "dbi:Driver:databasename".
  5804.  
  5805. =head2 DBI_DRIVER
  5806.  
  5807. The DBI_DRIVER environment variable is used to fill in the database
  5808. driver name in DBI->connect if the data source string starts "dbi::"
  5809. (thereby omitting the driver).
  5810. If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap.
  5811.  
  5812. =head2 DBI_AUTOPROXY
  5813.  
  5814. The DBI_AUTOPROXY environment variable takes a string value that starts
  5815. "dbi:Proxy:" and is typically followed by "hostname=...;port=...".
  5816. It is used to alter the behaviour of DBI->connect.
  5817. For full details, see DBI::Proxy documentation.
  5818.  
  5819. =head2 DBI_USER
  5820.  
  5821. The DBI_USER environment variable takes a string value that is used as
  5822. the user name if the DBI->connect call is given undef (as distinct from
  5823. an empty string) as the username argument.
  5824. Be wary of the security implications of using this.
  5825.  
  5826. =head2 DBI_PASS
  5827.  
  5828. The DBI_PASS environment variable takes a string value that is used as
  5829. the password if the DBI->connect call is given undef (as distinct from
  5830. an empty string) as the password argument.
  5831. Be extra wary of the security implications of using this.
  5832.  
  5833. =head2 DBI_DBNAME (obsolete)
  5834.  
  5835. The DBI_DBNAME environment variable takes a string value that is used only when the
  5836. obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and
  5837. when no value is provided for the first (database name) argument.
  5838.  
  5839. =head2 DBI_TRACE
  5840.  
  5841. The DBI_TRACE environment variable takes an integer value that
  5842. specifies the trace level for DBI at startup. Can also be used to
  5843. direct trace output to a file. See L</DEBUGGING> for more information.
  5844.  
  5845. =head2 PERL_DBI_DEBUG (obsolete)
  5846.  
  5847. An old variable that should no longer be used; equivalent to DBI_TRACE.
  5848.  
  5849. =head2 DBI_PROFILE
  5850.  
  5851. The DBI_PROFILE environment variable can be used to enable profiling
  5852. of DBI method calls. See <DBI::Profile> for more information.
  5853.  
  5854. =head2 DBI_PUREPERL
  5855.  
  5856. The DBI_PUREPERL environment variable can be used to enable the
  5857. use of DBI::PurePerl.  See <DBI::PurePerl> for more information.
  5858.  
  5859. =head1 WARNING AND ERROR MESSAGES
  5860.  
  5861. =head2 Fatal Errors
  5862.  
  5863. =over 4
  5864.  
  5865. =item Can't call method "prepare" without a package or object reference
  5866.  
  5867. The C<$dbh> handle you're using to call C<prepare> is probably undefined because
  5868. the preceding C<connect> failed. You should always check the return status of
  5869. DBI methods, or use the L</RaiseError> attribute.
  5870.  
  5871. =item Can't call method "execute" without a package or object reference
  5872.  
  5873. The C<$sth> handle you're using to call C<execute> is probably undefined because
  5874. the preceeding C<prepare> failed. You should always check the return status of
  5875. DBI methods, or use the L</RaiseError> attribute.
  5876.  
  5877. =item DBI/DBD internal version mismatch
  5878.  
  5879. The DBD driver module was built with a different version of DBI than
  5880. the one currently being used.  You should rebuild the DBD module under
  5881. the current version of DBI.
  5882.  
  5883. (Some rare platforms require "static linking". On those platforms, there
  5884. may be an old DBI or DBD driver version actually embedded in the Perl
  5885. executable being used.)
  5886.  
  5887. =item DBD driver has not implemented the AutoCommit attribute
  5888.  
  5889. The DBD driver implementation is incomplete. Consult the author.
  5890.  
  5891. =item Can't [sg]et %s->{%s}: unrecognised attribute
  5892.  
  5893. You attempted to set or get an unknown attribute of a handle.  Make
  5894. sure you have spelled the attribute name correctly; case is significant
  5895. (e.g., "Autocommit" is not the same as "AutoCommit").
  5896.  
  5897. =back
  5898.  
  5899. =head1 Pure-Perl DBI
  5900.  
  5901. A pure-perl emulation of the DBI is included in the distribution
  5902. for people using pure-perl drivers who, for whatever reason, can't
  5903. install the compiled DBI. See L<DBI::PurePerl>.
  5904.  
  5905. =head1 SEE ALSO
  5906.  
  5907. =head2 Driver and Database Documentation
  5908.  
  5909. Refer to the documentation for the DBD driver that you are using.
  5910.  
  5911. Refer to the SQL Language Reference Manual for the database engine that you are using.
  5912.  
  5913. =head2 ODBC and SQL/CLI Standards Reference Information
  5914.  
  5915. More detailed information about the semantics of certain DBI methods
  5916. that are based on ODBC and SQL/CLI standards is available on-line
  5917. via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI
  5918. standard:
  5919.  
  5920.  DBI method        ODBC function     SQL/CLI Working Draft
  5921.  ----------        -------------     ---------------------
  5922.  column_info       SQLColumns        Page 124
  5923.  foreign_key_info  SQLForeignKeys    Page 163
  5924.  get_info          SQLGetInfo        Page 214
  5925.  primary_key_info  SQLPrimaryKeys    Page 254
  5926.  table_info        SQLTables         Page 294
  5927.  type_info         SQLGetTypeInfo    Page 239
  5928.  
  5929. For example, for ODBC information on SQLColumns you'd visit:
  5930.  
  5931.   http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp
  5932.  
  5933. If that URL ceases to work then use the MSDN search facility at:
  5934.  
  5935.   http://search.microsoft.com/us/dev/
  5936.  
  5937. and search for C<SQLColumns returns> using the exact phrase option.
  5938. The link you want will probably just be called C<SQLColumns> and will
  5939. be part of the Data Access SDK.
  5940.  
  5941. And for SQL/CLI standard information on SQLColumns you'd read page 124 of
  5942. the (very large) SQL/CLI Working Draft available from:
  5943.  
  5944.   http://www.jtc1sc32.org/sc32/jtc1sc32.nsf/Attachments/7E3B41486BD99C3488256B410064C877/$FILE/32N0744T.PDF
  5945.  
  5946. =head2 SQL Standards Reference Information
  5947.  
  5948. A hyperlinked, browsable version of the BNF syntax for SQL92 (plus
  5949. Oracle 7 SQL and PL/SQL) is available here:
  5950.  
  5951.   http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html
  5952.  
  5953. A BNF syntax for SQL3 is available here:
  5954.  
  5955.   http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf
  5956.  
  5957. The following links provide further useful information about SQL.
  5958. Some of these are rather dated now but may still be useful.
  5959.  
  5960.   http://www.jcc.com/SQLPages/jccs_sql.htm
  5961.   http://www.contrib.andrew.cmu.edu/~shadow/sql.html
  5962.   http://www.altavista.com/query?q=sql+tutorial
  5963.  
  5964.  
  5965. =head2 Books and Journals
  5966.  
  5967.  Programming the Perl DBI, by Alligator Descartes and Tim Bunce.
  5968.  
  5969.  Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant.
  5970.  
  5971.  Learning Perl by Randal Schwartz.
  5972.  
  5973.  Dr Dobb's Journal, November 1996.
  5974.  
  5975.  The Perl Journal, April 1997.
  5976.  
  5977. =head2 Perl Modules
  5978.  
  5979. Index of DBI related modules available from CPAN:
  5980.  
  5981.  http://search.cpan.org/search?mode=module&query=DBIx%3A%3A
  5982.  http://search.cpan.org/search?mode=doc&query=DBI
  5983.  
  5984. For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers
  5985. (including Class::DBI, Alzabo, and DBIx::RecordSet in the former
  5986. category and Tangram and SPOPS in the latter) see the Perl
  5987. Object-Oriented Persistence project pages at:
  5988.  
  5989.  http://poop.sourceforge.net
  5990.  
  5991. A similar page for Java toolkits can be found at:
  5992.  
  5993.  http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison
  5994.  
  5995. =head2 Manual Pages
  5996.  
  5997. L<perl(1)>, L<perlmod(1)>, L<perlbook(1)>
  5998.  
  5999. =head2 Mailing List
  6000.  
  6001. The I<dbi-users> mailing list is the primary means of communication among
  6002. users of the DBI and its related modules. For details send email to:
  6003.  
  6004.  dbi-users-help@perl.org
  6005.  
  6006. There are typically between 700 and 900 messages per month.  You have
  6007. to subscribe in order to be able to post. However you can opt for a
  6008. 'post-only' subscription.
  6009.  
  6010. Mailing list archives (of variable quality) are held at:
  6011.  
  6012.  http://www.xray.mpe.mpg.de/mailing-lists/dbi/
  6013.  http://groups.yahoo.com/group/dbi-users
  6014.  http://www.bitmechanic.com/mail-archives/dbi-users/
  6015.  http://marc.theaimsgroup.com/?l=perl-dbi&r=1&w=2
  6016.  http://www.mail-archive.com/dbi-users%40perl.org/
  6017.  
  6018. =head2 Assorted Related WWW Links
  6019.  
  6020. The DBI "Home Page":
  6021.  
  6022.  http://dbi.perl.org/
  6023.  
  6024. Other DBI related links:
  6025.  
  6026.  http://tegan.deltanet.com/~phlip/DBUIdoc.html
  6027.  http://dc.pm.org/perl_db.html
  6028.  http://wdvl.com/Authoring/DB/Intro/toc.html
  6029.  http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html
  6030.  http://bumppo.net/lists/macperl/1999/06/msg00197.html
  6031.  http://gmax.oltrelinux.com/dbirecipes.html
  6032.  
  6033. Other database related links:
  6034.  
  6035.  http://www.jcc.com/sql_stnd.html
  6036.  http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html
  6037.  
  6038. Security, especially the "SQL Injection" attack:
  6039.  
  6040.  http://www.ngssoftware.com/research/papers.html
  6041.  http://www.ngssoftware.com/papers/advanced_sql_injection.pdf
  6042.  http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf
  6043.  http://www.esecurityplanet.com/trends/article.php/2243461
  6044.  http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf
  6045.  http://www.webcohort.com/Blindfolded_SQL_Injection.pdf
  6046.  http://online.securityfocus.com/infocus/1644
  6047.  
  6048. Commercial and Data Warehouse Links
  6049.  
  6050.  http://www.dwinfocenter.org
  6051.  http://www.datawarehouse.com
  6052.  http://www.datamining.org
  6053.  http://www.olapcouncil.org
  6054.  http://www.idwa.org
  6055.  http://www.knowledgecenters.org/dwcenter.asp
  6056.  
  6057. Recommended Perl Programming Links
  6058.  
  6059.  http://language.perl.com/style/
  6060.  
  6061.  
  6062. =head2 FAQ
  6063.  
  6064. Please also read the DBI FAQ which is installed as a DBI::FAQ module.
  6065. You can use I<perldoc> to read it by executing the C<perldoc DBI::FAQ> command.
  6066.  
  6067. =head1 AUTHORS
  6068.  
  6069. DBI by Tim Bunce.  This pod text by Tim Bunce, J. Douglas Dunlop,
  6070. Jonathan Leffler and others.  Perl by Larry Wall and the
  6071. C<perl5-porters>.
  6072.  
  6073. =head1 COPYRIGHT
  6074.  
  6075. The DBI module is Copyright (c) 1994-2003 Tim Bunce. Ireland.
  6076. All rights reserved.
  6077.  
  6078. You may distribute under the terms of either the GNU General Public
  6079. License or the Artistic License, as specified in the Perl README file.
  6080.  
  6081. =head1 ACKNOWLEDGEMENTS
  6082.  
  6083. I would like to acknowledge the valuable contributions of the many
  6084. people I have worked with on the DBI project, especially in the early
  6085. years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti,
  6086. Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler,
  6087. Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander,
  6088. Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson,
  6089. Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen,
  6090. Steve Baumgarten, Randal Schwartz, and a whole lot more.
  6091.  
  6092. Then, of course, there are the poor souls who have struggled through
  6093. untold and undocumented obstacles to actually implement DBI drivers.
  6094. Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan
  6095. Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo,
  6096. Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve
  6097. Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would
  6098. not be the practical reality it is today.  I'm also especially grateful
  6099. to Alligator Descartes for starting work on the "Programming the Perl
  6100. DBI" book and letting me jump on board.
  6101.  
  6102. Much of the DBI and DBD::Oracle was developed while I was Technical
  6103. Director (CTO) of the Paul Ingram Group (www.ig.co.uk).  So I'd
  6104. especially like to thank Paul for his generosity and vision in
  6105. supporting this work for many years.
  6106.  
  6107. =head1 TRANSLATIONS
  6108.  
  6109. A German translation of this manual (possibly slightly out of date) is
  6110. available, thanks to O'Reilly, at:
  6111.  
  6112.   http://www.oreilly.de/catalog/perldbiger/
  6113.  
  6114. Some other translations:
  6115.  
  6116.  http://cronopio.net/perl/                              - Spanish
  6117.  http://member.nifty.ne.jp/hippo2000/dbimemo.htm        - Japanese
  6118.  
  6119.  
  6120. =head1 SUPPORT / WARRANTY
  6121.  
  6122. The DBI is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
  6123.  
  6124. Commercial support for Perl and the DBI, DBD::Oracle and
  6125. Oraperl modules can be arranged via The Perl Clinic.
  6126. For more details visit:
  6127.  
  6128.   http://www.perlclinic.com
  6129.  
  6130. For direct DBI and DBD::Oracle support, enhancement, and related work
  6131. I am available for consultancy on standard commercial terms.
  6132.  
  6133.  
  6134. =head1 TRAINING
  6135.  
  6136. References to DBI related training resources. No recommendation implied.
  6137.  
  6138.   http://www.treepax.co.uk/
  6139.   http://www.keller.com/dbweb/
  6140.  
  6141. =head1 FREQUENTLY ASKED QUESTIONS
  6142.  
  6143. See the DBI FAQ for a more comprehensive list of FAQs. Use the
  6144. C<perldoc DBI::FAQ> command to read it.
  6145.  
  6146. =head2 How fast is the DBI?
  6147.  
  6148. To measure the speed of the DBI and DBD::Oracle code, I modified
  6149. DBD::Oracle so you can set an attribute that will cause the
  6150. same row to be fetched from the row cache over and over again (without
  6151. involving Oracle code but exercising *all* the DBI and DBD::Oracle code
  6152. in the code path for a fetch).
  6153.  
  6154. The results (on my lightly loaded old Sparc 10) fetching 50000 rows using:
  6155.  
  6156.     1 while $csr->fetch;
  6157.  
  6158. were:
  6159.     one field:   5300 fetches per cpu second (approx)
  6160.     ten fields:  4000 fetches per cpu second (approx)
  6161.  
  6162. Obviously results will vary between platforms (newer faster platforms
  6163. can reach around 50000 fetches per second), but it does give a feel for
  6164. the maximum performance: fast.  By way of comparison, using the code:
  6165.  
  6166.     1 while @row = $csr->fetchrow_array;
  6167.  
  6168. (C<fetchrow_array> is roughly the same as C<ora_fetch>) gives:
  6169.  
  6170.     one field:   3100 fetches per cpu second (approx)
  6171.     ten fields:  1000 fetches per cpu second (approx)
  6172.  
  6173. Notice the slowdown and the more dramatic impact of extra fields.
  6174. (The fields were all one char long. The impact would be even bigger for
  6175. longer strings.)
  6176.  
  6177. Changing that slightly to represent actually doing something in Perl
  6178. with the fetched data:
  6179.  
  6180.     while(@row = $csr->fetchrow_array) {
  6181.         $hash{++$i} = [ @row ];
  6182.     }
  6183.  
  6184. gives:    ten fields:  500 fetches per cpu second (approx)
  6185.  
  6186. That simple addition has *halved* the performance.
  6187.  
  6188. I therefore conclude that DBI and DBD::Oracle overheads are small
  6189. compared with Perl language overheads (and probably database overheads).
  6190.  
  6191. So, if you think the DBI or your driver is slow, try replacing your
  6192. fetch loop with just:
  6193.  
  6194.     1 while $csr->fetch;
  6195.  
  6196. and time that. If that helps then point the finger at your own code. If
  6197. that doesn't help much then point the finger at the database, the
  6198. platform, the network etc. But think carefully before pointing it at
  6199. the DBI or your driver.
  6200.  
  6201. (Having said all that, if anyone can show me how to make the DBI or
  6202. drivers even more efficient, I'm all ears.)
  6203.  
  6204.  
  6205. =head2 Why doesn't my CGI script work right?
  6206.  
  6207. Read the information in the references below.  Please do I<not> post
  6208. CGI related questions to the I<dbi-users> mailing list (or to me).
  6209.  
  6210.  http://www.perl.com/cgi-bin/pace/pub/doc/FAQs/cgi/perl-cgi-faq.html
  6211.  http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
  6212.  http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
  6213.  http://www.boutell.com/faq/
  6214.  http://www.perl.com/perl/faq/
  6215.  
  6216. =head2 How can I maintain a WWW connection to a database?
  6217.  
  6218. For information on the Apache httpd server and the C<mod_perl> module see
  6219.  
  6220.   http://perl.apache.org/
  6221.  
  6222. =head2 What about ODBC?
  6223.  
  6224. A DBD::ODBC driver module for ODBC is available and works well.
  6225.  
  6226. =head2 Does the DBI have a year 2000 problem?
  6227.  
  6228. No. The DBI has no knowledge or understanding of dates at all.
  6229.  
  6230. Individual drivers (DBD::*) may have some date handling code but are
  6231. unlikely to have year 2000 related problems within their code. However,
  6232. your application code which I<uses> the DBI and DBD drivers may have
  6233. year 2000 related problems if it has not been designed and written well.
  6234.  
  6235. See also the "Does Perl have a year 2000 problem?" section of the Perl FAQ:
  6236.  
  6237.   http://www.perl.com/CPAN/doc/FAQs/FAQ/PerlFAQ.html
  6238.  
  6239. =head1 OTHER RELATED WORK AND PERL MODULES
  6240.  
  6241. =over 4
  6242.  
  6243. =item Apache::DBI by E.Mergl@bawue.de
  6244.  
  6245. To be used with the Apache daemon together with an embedded Perl
  6246. interpreter like C<mod_perl>. Establishes a database connection which
  6247. remains open for the lifetime of the HTTP daemon. This way the CGI
  6248. connect and disconnect for every database access becomes superfluous.
  6249.  
  6250. =item JDBC Server by Stuart 'Zen' Bishop zen@bf.rmit.edu.au
  6251.  
  6252. The server is written in Perl. The client classes that talk to it are
  6253. of course in Java. Thus, a Java applet or application will be able to
  6254. comunicate via the JDBC API with any database that has a DBI driver installed.
  6255. The URL used is in the form C<jdbc:dbi://host.domain.etc:999/Driver/DBName>.
  6256. It seems to be very similar to some commercial products, such as jdbcKona.
  6257.  
  6258. =item Remote Proxy DBD support
  6259.  
  6260. As of DBI 1.02, a complete implementation of a DBD::Proxy driver and the
  6261. DBI::ProxyServer are part of the DBI distribution.
  6262.  
  6263. =item SQL Parser
  6264.  
  6265. See also the SQL::Statement module, SQL parser and engine.
  6266.  
  6267. =back
  6268.  
  6269. =cut
  6270.